<template>
  <div class="employees-container">
    <div class="header">
      <h2>简历管理</h2>
      <div class="header-buttons">
        <el-button type="primary" @click="handleAddResume">
          <el-icon><Plus /></el-icon>
          <span>新增</span>
        </el-button>
        <el-button type="success" @click="handleExportExcel" style="margin-left: 10px;">
          <el-icon><Download /></el-icon>
          <span>导出Excel</span>
        </el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索简历姓名"
        style="width: 200px"
        clearable
        @clear="handleSearch"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <div class="table-container">
      <el-table 
        :data="filteredEmployees" 
        style="width: 100%" 
        :fit="true" 
        size="small"
      >
        <el-table-column prop="name" label="姓名" min-width="80" />
        <el-table-column prop="phone" label="联系电话" min-width="120" />
        <el-table-column prop="school" label="毕业院校" min-width="150" />
        <el-table-column prop="major" label="专业" min-width="120" />
        <el-table-column label="学历" min-width="80">
          <template #default="scope">
            {{ degreeOptions.find(item => item.value === scope.row.degree)?.label || scope.row.degree }}
          </template>
        </el-table-column>
        <el-table-column label="工作年限" min-width="80">
          <template #default="scope">
            {{ calculateWorkYears(scope.row.graduation_date) }}
          </template>
        </el-table-column>
        <el-table-column label="外语水平" min-width="80">
          <template #default="scope">
            {{ scope.row.language_level && Array.isArray(scope.row.language_level) ? scope.row.language_level.map(value => languageLevelOptions.find(item => item.value === value)?.label || value).join(', ') : scope.row.language_level }}
          </template>
        </el-table-column>
        <el-table-column prop="position" label="现任职务" min-width="120" />
        <el-table-column label="合同起止日期" min-width="200">
          <template #default="scope">
            {{ scope.row.contract_period_start ? `${scope.row.contract_period_start} 至 ${scope.row.contract_period_end}` : '未设置' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="300" fixed="right">
          <template #default="scope">
            <el-button size="small" type="warning" @click="handleViewDetails(scope.row)">
              <el-icon><View /></el-icon>
              <span>查看</span>
            </el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>
              <span>编辑</span>
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>
              <span>删除</span>
            </el-button>
            <el-button size="small" type="success" @click="handleExport(scope.row)">
              <el-icon><Download /></el-icon>
              <span>导出</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog
      v-model="showDialog"
      :title="dialogTitle"
      width="70%"
      @close="handleMainDialogClose"
    >
      <el-tabs v-model="activeEditTab" @tab-click="handleTabClick">
        <!-- 基本信息标签页 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="120px"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="form.name" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="编号" prop="number">
                  <el-input v-model="form.number" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="入职时间" prop="entry_time">
                  <el-date-picker
                    v-model="form.entry_time"
                    type="date"
                    placeholder="选择日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="gender">
                  <DictRadio v-model="form.gender" type="GENDER" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="出生年月" prop="birth_date">
                  <el-date-picker
                    v-model="form.birth_date"
                    type="date"
                    placeholder="选择日期"
                    format="YYYY.MM"
                    value-format="YYYY.MM"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="年龄">
                  <el-input :model-value="calculateAge(form.birth_date)" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="民族" prop="ethnicity">
                  <el-select v-model="form.ethnicity" placeholder="请选择民族" filterable style="width: 100%">
                    <el-option v-for="item in ethnicityOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="籍贯" prop="native_place">
                  <el-input v-model="form.native_place" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="出生地" prop="birth_place">
                  <el-input v-model="form.birth_place" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="政治面貌" prop="political_status">
                  <DictRadio v-model="form.political_status" type="POLITICAL_STATUS" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="婚姻状况" prop="marital_status">
                  <DictRadio v-model="form.marital_status" type="MARITAL_STATUS" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="健康状况" prop="health_status">
                  <el-input v-model="form.health_status" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="毕业院校" prop="school">
                  <el-input v-model="form.school" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="专业" prop="major">
                  <el-input v-model="form.major" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="学历" prop="degree">
                  <el-select v-model="form.degree" placeholder="请选择学历" filterable style="width: 100%">
                    <el-option v-for="item in degreeOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="学位" prop="academic_degree">
                  <el-select v-model="form.academic_degree" placeholder="请选择学位" filterable style="width: 100%">
                    <el-option v-for="item in academicDegreeOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="毕业时间" prop="graduation_date">
                  <el-date-picker
                    v-model="form.graduation_date"
                    type="date"
                    placeholder="选择日期"
                    format="YYYY.MM"
                    value-format="YYYY.MM"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="外语水平" prop="language_level">
                  <el-select
                    v-model="form.language_level"
                    placeholder="请选择外语水平"
                    multiple
                    filterable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in languageLevelOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="职称" prop="title">
                  <el-input v-model="form.title" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="岗位工作时间" prop="position_start_date">
                  <el-date-picker
                    v-model="form.position_start_date"
                    type="date"
                    placeholder="选择日期"
                    format="YYYY.MM"
                    value-format="YYYY.MM"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="工作年限">
                  <el-input-number :model-value="workYears" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="岗位相关工作年限">
                  <el-input-number :model-value="positionYears" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 现任职务 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="部门" prop="department">
                  <el-input v-model="form.department" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="现任职务" prop="position">
                  <el-input v-model="form.position" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="现居住地址" prop="current_address">
                  <el-input v-model="form.current_address" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="form.phone" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号码" prop="id_number">
                  <el-input v-model="form.id_number" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="户口所在地" prop="household_address">
                  <el-input v-model="form.household_address" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="紧急联系人" prop="emergency_contact">
                  <el-input v-model="form.emergency_contact" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="紧急联系电话" prop="emergency_phone">
                  <el-input v-model="form.emergency_phone" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="获奖情况" prop="awards">
                  <el-input
                    v-model="form.awards"
                    type="textarea"
                    :rows="5"
                    placeholder="请输入获奖情况"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>

        <!-- 教育背景标签页 -->
        <el-tab-pane label="教育背景" name="education">
          <div v-if="showDialog">
            <div class="tab-header">
              <el-button type="primary" @click="handleAddEducation">添加教育背景</el-button>
            </div>
            <el-table
              :data="educations"
              style="width: 100%"
              :fit="true"
              size="small"
              v-loading="educationLoading"
            >
              <el-table-column prop="degree" label="学历" min-width="80" />
              <el-table-column prop="major" label="专业" min-width="120" />
              <el-table-column prop="school" label="毕业院校" min-width="150" />
              <el-table-column prop="graduation_date" label="毕业时间" min-width="120">
                <template #default="scope">
                  {{ formatDate(scope.row.graduation_date) }}
                </template>
              </el-table-column>
              <el-table-column prop="degree_type" label="学历性质" min-width="100" />
              <el-table-column prop="is_double_certificate" label="是否双证" min-width="80">
                <template #default="scope">
                  <el-tag :type="scope.row.is_double_certificate ? 'success' : 'info'">
                    {{ scope.row.is_double_certificate ? '是' : '否' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="220" fixed="right">
                <template #default="scope">
                  <el-button size="small" type="warning" @click="handleViewEducation(scope.row)">查看</el-button>
                  <el-button size="small" type="primary" @click="handleEditEducation(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="handleDeleteEducation(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination" style="margin-top: 10px; text-align: right;">
              <el-pagination
                v-model:current-page="educationPage"
                v-model:page-size="educationPageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next"
                :total="educationTotal"
                @size-change="handleEducationSizeChange"
                @current-change="handleEducationPageChange"
              />
            </div>
            <el-dialog v-model="showEducationDialog" :title="educationDialogTitle" width="50%" :destroy-on-close="true">
              <el-form :model="educationForm" label-width="120px">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="学历" prop="degree">
                      <el-select v-model="educationForm.degree">
                        <el-option label="本科" value="本科" />
                        <el-option label="硕士" value="硕士" />
                        <el-option label="博士" value="博士" />
                        <el-option label="大专" value="大专" />
                        <el-option label="中专" value="中专" />
                        <el-option label="高中" value="高中" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="专业" prop="major">
                      <el-input v-model="educationForm.major" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="毕业院校" prop="school">
                      <el-input v-model="educationForm.school" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="毕业时间" prop="graduation_date">
                      <el-date-picker v-model="educationForm.graduation_date" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="学历性质" prop="degree_type">
                      <el-select v-model="educationForm.degree_type">
                        <el-option label="全日制" value="全日制" />
                        <el-option label="自考" value="自考" />
                        <el-option label="成教" value="成教" />
                        <el-option label="国开" value="国开" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="是否双证" prop="is_double_certificate">
                      <el-radio-group v-model="educationForm.is_double_certificate">
                        <el-radio-button :label="true">是</el-radio-button>
                        <el-radio-button :label="false">否</el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="showEducationDialog = false">取消</el-button>
                  <el-button type="primary" @click="handleSaveEducation">保存</el-button>
                </span>
              </template>
            </el-dialog>
          </div>
          <div v-else-if="showDetailsDialog">
            <el-table
              :data="educations"
              style="width: 100%"
              :fit="true"
              size="small"
              v-loading="educationLoading"
            >
              <el-table-column prop="degree" label="学历" min-width="80" />
              <el-table-column prop="major" label="专业" min-width="120" />
              <el-table-column prop="school" label="毕业院校" min-width="150" />
              <el-table-column prop="graduation_date" label="毕业时间" min-width="120">
                <template #default="scope">
                  {{ formatDate(scope.row.graduation_date) }}
                </template>
              </el-table-column>
              <el-table-column prop="degree_type" label="学历性质" min-width="100" />
              <el-table-column prop="is_double_certificate" label="是否双证" min-width="80">
                <template #default="scope">
                  <el-tag :type="scope.row.is_double_certificate ? 'success' : 'info'">
                    {{ scope.row.is_double_certificate ? '是' : '否' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" fixed="right">
                <template #default="scope">
                  <el-button size="small" type="warning" @click="handleViewEducation(scope.row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination" style="margin-top: 10px; text-align: right;">
              <el-pagination
                v-model:current-page="educationPage"
                v-model:page-size="educationPageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next"
                :total="educationTotal"
                @size-change="handleEducationSizeChange"
                @current-change="handleEducationPageChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <!-- 获得证书标签页 -->
        <el-tab-pane label="获得证书" name="certificates">
          <div v-if="showDialog">
            <div class="tab-header">
              <el-button type="primary" @click="() => { certDialogMode = 'add'; currentCertificate = null; showCertDialog = true }">添加证书</el-button>
            </div>
            <div class="table-container" style="height: 100%; display: flex; flex-direction: column; overflow-x: auto;">
              <el-table
                :data="employeeCertificates"
                style="width: 100%; min-width: 1200px;"
                v-loading="certLoading"
                :fit="true"
                size="small"
              >
                <el-table-column prop="name" label="证书名称" min-width="180" show-overflow-tooltip />
                <el-table-column prop="certificate_no" label="证书编号" min-width="150" show-overflow-tooltip />
                <el-table-column prop="level" label="证书级别" width="120" show-overflow-tooltip />
                <el-table-column prop="issuing_org" label="发证机构" min-width="180" show-overflow-tooltip />
                <el-table-column prop="issue_date" label="获得日期" width="120">
                  <template #default="scope">
                    {{ formatDate(scope.row.issue_date) }}
                  </template>
                </el-table-column>
                <el-table-column prop="expiry_date" label="有效期" width="120">
                  <template #default="scope">
                    {{ formatDate(scope.row.expiry_date) }}
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="备注说明" min-width="150" show-overflow-tooltip />
                <el-table-column label="操作" width="220" fixed="right">
                  <template #default="scope">
                    <el-button size="small" type="warning" @click="handleCertView(scope.row)">查看</el-button>
                    <el-button size="small" type="primary" @click="handleCertEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleCertDelete(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="pagination" style="flex-shrink: 0;">
                <el-pagination
                  v-model:current-page="certPage"
                  v-model:page-size="certPageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next"
                  :total="certTotal"
                  @size-change="handleCertSizeChange"
                  @current-change="handleCertCurrentChange"
                />
              </div>
            </div>
            <el-dialog v-model="showCertDialog" title="证书详情" width="80%" style="max-width: 1200px" :destroy-on-close="true" class="certificate-dialog">
              <div class="dialog-content">
                <certificate-form
                  v-if="showCertDialog"
                  :mode="certDialogMode"
                  :certificate="currentCertificate"
                  :employee-id="currentEmployeeId"
                  @close="showCertDialog = false"
                />
              </div>
            </el-dialog>
          </div>
          <div v-else-if="showDetailsDialog">
            <div class="table-container" style="height: 100%; display: flex; flex-direction: column; overflow-x: auto;">
              <el-table
                :data="employeeCertificates"
                style="width: 100%; min-width: 1200px;"
                v-loading="certLoading"
                :fit="true"
                size="small"
              >
                <el-table-column prop="name" label="证书名称" min-width="180" show-overflow-tooltip />
                <el-table-column prop="certificate_no" label="证书编号" min-width="150" show-overflow-tooltip />
                <el-table-column prop="level" label="证书级别" width="120" show-overflow-tooltip />
                <el-table-column prop="issuing_org" label="发证机构" min-width="180" show-overflow-tooltip />
                <el-table-column prop="issue_date" label="获得日期" width="120">
                  <template #default="scope">
                    {{ formatDate(scope.row.issue_date) }}
                  </template>
                </el-table-column>
                <el-table-column prop="expiry_date" label="有效期" width="120">
                  <template #default="scope">
                    {{ formatDate(scope.row.expiry_date) }}
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="备注说明" min-width="150" show-overflow-tooltip />
                <el-table-column label="操作" width="100" fixed="right">
                  <template #default="scope">
                    <el-button size="small" type="warning" @click="handleCertView(scope.row)">查看</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="pagination" style="flex-shrink: 0;">
                <el-pagination
                  v-model:current-page="certPage"
                  v-model:page-size="certPageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next"
                  :total="certTotal"
                  @size-change="handleCertSizeChange"
                  @current-change="handleCertCurrentChange"
                />
              </div>
            </div>
            <el-dialog v-model="showCertDialog" title="证书详情" width="80%" style="max-width: 1200px" :destroy-on-close="true" class="certificate-dialog">
              <div class="dialog-content">
                <certificate-form
                  v-if="showCertDialog"
                  :mode="certDialogMode"
                  :certificate="currentCertificate"
                  :employee-id="currentEmployeeId"
                  @close="showCertDialog = false"
                />
              </div>
            </el-dialog>
          </div>
        </el-tab-pane>

        <!-- 个人专业技能标签页 -->
        <el-tab-pane label="个人专业技能" name="skills">
          <div style="border: 1px solid #ccc" v-if="activeEditTab === 'skills'">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
            />
            <Editor
              style="height: 400px; overflow-y: hidden;"
              v-model="form.skills"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="handleEditorCreated"
              @onDestroyed="handleEditorDestroyed"
              @onChange="handleEditorChange"
            />
          </div>
        </el-tab-pane>

        <!-- 项目经验标签页 -->
        <el-tab-pane label="项目经验" name="projects">
          <div class="tab-header">
            <el-button type="primary" @click="showProjectDialog = true">添加项目经验</el-button>
          </div>
          <el-table 
            :data="projects" 
            style="width: 100%"
            :fit="true"
            size="small"
          >
            <el-table-column prop="name" label="项目名称" min-width="120" />
            <el-table-column prop="client_name" label="客户名称" min-width="120" />
            <el-table-column prop="role" label="担任角色" min-width="100" />
            <el-table-column prop="start_date" label="开始日期" min-width="100" />
            <el-table-column prop="end_date" label="结束日期" min-width="100" />
            <el-table-column prop="responsibilities" label="主要职责" min-width="200" />
            <el-table-column label="操作" width="300" fixed="right">
              <template #default="scope">
                <el-button size="small" type="warning" @click="handleViewProject(scope.row)">查看</el-button>
                <el-button size="small" type="primary" @click="handleEditProject(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDeleteProject(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination" style="margin-top: 10px; text-align: right;">
            <el-pagination
              v-model:current-page="projectsPage"
              v-model:page-size="projectsPageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next"
              :total="projectsTotal"
              @size-change="handleProjectsSizeChange"
              @current-change="handleProjectsPageChange"
            />
          </div>
        </el-tab-pane>

        <!-- 工作经历标签页 -->
        <el-tab-pane label="工作经历" name="workExperience">
          <div class="tab-header">
            <el-button type="primary" @click="handleAddWorkExperience">添加工作经历</el-button>
          </div>
          <el-table 
            :data="workExperiences" 
            style="width: 100%"
            :fit="true"
            size="small"
          >
            <el-table-column prop="company" label="公司名称" min-width="150" />
            <el-table-column prop="department" label="所在部门" min-width="120" />
            <el-table-column prop="position" label="职位" min-width="120" />
            <el-table-column prop="start_date" label="开始日期" min-width="100" />
            <el-table-column label="结束日期" min-width="100">
              <template #default="scope">
                {{ scope.row.end_date || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="description" label="工作描述" min-width="200" />
            <el-table-column prop="reference" label="证明人" min-width="100" />
            <el-table-column prop="reference_phone" label="证明人电话" min-width="120" />
            <el-table-column label="操作" width="300" fixed="right">
              <template #default="scope">
                <el-button size="small" type="warning" @click="handleViewWorkExperience(scope.row)">查看</el-button>
                <el-button size="small" type="primary" @click="handleEditWorkExperience(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDeleteWorkExperience(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination" style="margin-top: 10px; text-align: right;">
            <el-pagination
              v-model:current-page="workPage"
              v-model:page-size="workPageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next"
              :total="workTotal"
              @size-change="handleWorkSizeChange"
              @current-change="handleWorkPageChange"
            />
          </div>
        </el-tab-pane>

        <!-- 培训经历标签页 -->
        <el-tab-pane label="培训经历" name="trainingExperience">
          <div v-if="showDialog" class="tab-header" style="margin-bottom: 10px;">
            <el-button type="primary" @click="() => { trainingDialogTitle = '添加培训经历'; trainingForm = { course_name: '', organization: '', start_date: '', end_date: '', certificate: '' }; showTrainingDialog = true }">添加培训经历</el-button>
          </div>
          <el-table :data="trainingExperiences" style="width: 100%" :fit="true" size="small">
            <el-table-column prop="course_name" label="培训课程名称" min-width="150" />
            <el-table-column prop="organization" label="培训机构" min-width="120" />
            <el-table-column label="培训时间" min-width="180">
              <template #default="scope">
                {{ scope.row.start_date }} 至 {{ scope.row.end_date }}
              </template>
            </el-table-column>
            <el-table-column prop="certificate" label="培训证书" min-width="120" />
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="scope">
                <el-button size="small" type="warning" @click="handleViewTraining(scope.row)">查看</el-button>
                <el-button v-if="showDialog" size="small" type="primary" @click="handleEditTraining(scope.row)">编辑</el-button>
                <el-button v-if="showDialog" size="small" type="danger" @click="handleDeleteTraining(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 培训经历编辑/新增弹窗 -->
          <el-dialog
            v-model="showTrainingDialog"
            :title="trainingDialogTitle"
            :width="'80%'"
            style="max-width: 1200px"
            :destroy-on-close="true"
          >
            <el-form :model="trainingForm" ref="trainingFormRef" label-width="120px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="培训课程名称" prop="course_name">
                    <el-input v-model="trainingForm.course_name" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="培训机构" prop="organization">
                    <el-input v-model="trainingForm.organization" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="开始日期" prop="start_date">
                    <el-date-picker v-model="trainingForm.start_date" type="date" placeholder="选择开始日期" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结束日期" prop="end_date">
                    <el-date-picker v-model="trainingForm.end_date" type="date" placeholder="选择结束日期" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="培训证书" prop="certificate">
                    <el-input v-model="trainingForm.certificate" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="描述" prop="description">
                    <el-input v-model="trainingForm.description" type="textarea" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="showTrainingDialog = false">取消</el-button>
                <el-button type="primary" @click="submitTrainingForm">保存</el-button>
              </span>
            </template>
          </el-dialog>
          <!-- 培训经历只读详情弹窗 -->
          <el-dialog v-model="showTrainingViewDialog" title="培训经历详情" width="80%" :style="{maxWidth: '1200px'}">
            <el-form label-width="120px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="培训课程名称">
                    <el-input :model-value="currentTrainingView.course_name" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="培训机构">
                    <el-input :model-value="currentTrainingView.organization" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="培训时间">
                    <el-input :model-value="(currentTrainingView.start_date || '') + ' 至 ' + (currentTrainingView.end_date || '')" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="培训证书">
                    <el-input :model-value="currentTrainingView.certificate" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item v-if="currentTrainingView.description" label="描述">
                    <el-input type="textarea" :model-value="currentTrainingView.description" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="showTrainingViewDialog = false">关闭</el-button>
              </span>
            </template>
          </el-dialog>
        </el-tab-pane>

        <!-- 合同信息标签页 -->
        <el-tab-pane label="合同信息" name="contracts">
          <div v-if="showDialog" class="tab-header" style="margin-bottom: 10px;">
            <el-button type="primary" @click="handleAddContract">添加合同</el-button>
          </div>
          <el-table :data="employeeContracts" style="width: 100%; min-width: 1200px;" :fit="true" size="small">
            <el-table-column prop="contract_number" label="合同编号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="contract_type" label="合同类型" min-width="100">
              <template #default="scope">
                <el-tag :type="scope.row.contract_type === '劳动合同' ? 'success' : (scope.row.contract_type === '劳务合同' ? 'warning' : 'info')">
                  {{ scope.row.contract_type }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="contract_party" label="合同主体" min-width="120" show-overflow-tooltip />
            <el-table-column prop="start_date" label="签订日期" min-width="120">
              <template #default="scope">
                {{ formatDate(scope.row.start_date) }}
              </template>
            </el-table-column>
            <el-table-column prop="end_date" label="到期日期" min-width="120">
              <template #default="scope">
                {{ formatDate(scope.row.end_date) }}
              </template>
            </el-table-column>
            <el-table-column label="合同年限" min-width="100">
              <template #default="scope">
                {{ calculateContractYears(scope.row.start_date, scope.row.end_date) }}
              </template>
            </el-table-column>
            <el-table-column prop="is_expired" label="合同状态" min-width="100">
              <template #default="scope">
                <el-tag :type="scope.row.is_expired ? 'danger' : 'success'">
                  {{ scope.row.is_expired ? '已到期' : '未到期' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="scope">
                <el-button size="small" type="warning" @click="handleViewContract(scope.row)">查看</el-button>
                <el-button v-if="showDialog" size="small" type="primary" @click="handleEditContract(scope.row)">编辑</el-button>
                <el-button v-if="showDialog" size="small" type="danger" @click="handleDeleteContract(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 档案资料标签页 -->
        <el-tab-pane label="档案资料" name="attachments">
          <div v-if="showDialog">
            <div class="contract-attachment-card attachment-card-with-label">
              <span class="attachment-card-label">附件列表</span>
              <AttachmentList
                v-if="activeEditTab === 'attachments'"
                :attachments="attachments"
                :loading="loadingAttachments"
                :readonly="false"
                module="employees"
                :moduleId="currentEmployee.id"
                :download-function="handleDownloadAttachment"
                :delete-function="handleDeleteAttachment"
                :preview-function="handlePreviewAttachment"
                @refresh="loadAttachments"
                @add-attachment="showAttachmentUploader = true"
              />
              <el-dialog v-model="showAttachmentUploader" title="上传附件" width="500px" destroy-on-close @closed="handleUploadDialogClosed">
                <AttachmentUploader
                  module="employees"
                  :moduleId="currentEmployee.id"
                  @upload-success="handleUploadSuccess"
                />
              </el-dialog>
            </div>
          </div>
          <div v-else-if="showDetailsDialog">
            <div class="contract-attachment-card attachment-card-with-label">
              <span class="attachment-card-label">附件列表</span>
              <AttachmentList
                v-if="activeEditTab === 'attachments'"
                :attachments="attachments"
                :loading="loadingAttachments"
                :readonly="true"
                module="employees"
                :moduleId="currentEmployee.id"
                :download-function="handleDownloadAttachment"
                :preview-function="handlePreviewAttachment"
              />
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="奖惩记录" name="rewardPunishment">
          <RewardPunishmentTable
            v-if="activeEditTab === 'rewardPunishment'"
            :employee-id="form.id || null"
            :readonly="!showDialog"
            :key="'edit-' + (form.id || '') + '-' + showDialog"
          />
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导出简历对话框 -->
    <el-dialog
      v-model="showExportDialog"
      title="导出简历"
      width="80%"
    >
      <div class="resume-preview">
        <!-- 基本信息 -->
        <div class="resume-section">
          <div class="info-container">
            <el-row class="info-row">
              <el-col :span="4" class="info-label">姓名</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.name }}</el-col>
              <el-col :span="4" class="info-label">性别</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.gender }}</el-col>
              <el-col :span="4" class="info-label">出生年月</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.birth_date }}</el-col>
            </el-row>
            <el-row class="info-row">
              <el-col :span="4" class="info-label">民族</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.ethnicity }}</el-col>
              <el-col :span="4" class="info-label">籍贯</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.native_place }}</el-col>
              <el-col :span="4" class="info-label">出生地</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.birth_place }}</el-col>
            </el-row>
            <el-row class="info-row">
              <el-col :span="4" class="info-label">政治面貌</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.political_status }}</el-col>
              <el-col :span="4" class="info-label">婚姻状况</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.marital_status }}</el-col>
              <el-col :span="4" class="info-label">健康状况</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.health_status }}</el-col>
            </el-row>
            <el-row class="info-row">
              <el-col :span="4" class="info-label">毕业院校</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.school }}</el-col>
              <el-col :span="4" class="info-label">专业</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.major }}</el-col>
              <el-col :span="4" class="info-label">学历</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.degree }}</el-col>
            </el-row>
            <el-row class="info-row">
              <el-col :span="4" class="info-label">毕业时间</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.graduation_date }}</el-col>
              <el-col :span="4" class="info-label">外语水平</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.language_level && Array.isArray(currentEmployee.language_level) ? currentEmployee.language_level.map(value => languageLevelOptions.find(item => item.value === value)?.label || value).join(', ') : currentEmployee.language_level }}</el-col>
              <el-col :span="4" class="info-label">职称</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.title }}</el-col>
            </el-row>
            <el-row class="info-row">
              <el-col :span="4" class="info-label">岗位工作时间</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.position_start_date }}</el-col>
              <el-col :span="4" class="info-label">工作年限</el-col>
              <el-col :span="4" class="info-value">{{ calculateWorkYears(currentEmployee.graduation_date) }}</el-col>
              <el-col :span="4" class="info-label">岗位相关工作年限</el-col>
              <el-col :span="4" class="info-value">{{ calculatePositionYears(currentEmployee.position_start_date) }}</el-col>
            </el-row>
            <el-row class="info-row">
              <el-col :span="4" class="info-label">现行劳动合同主体</el-col>
              <el-col :span="4" class="info-value">{{ latestContract?.contract_party || '-' }}</el-col>
              <el-col :span="4" class="info-label">现任职务</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.position || '-' }}</el-col>
              <el-col :span="4" class="info-label">合同起止日期</el-col>
              <el-col :span="4" class="info-value">
                <span v-if="latestContract">
                  {{ latestContract.start_date ? latestContract.start_date.slice(0, 10) : '-' }} 至 {{ latestContract.end_date ? latestContract.end_date.slice(0, 10) : '-' }}
                </span>
                <span v-else>-</span>
              </el-col>
            </el-row>
            <el-row class="info-row">
              <el-col :span="4" class="info-label">现居住地址</el-col>
              <el-col :span="12" class="info-value">{{ currentEmployee.current_address }}</el-col>
              <el-col :span="4" class="info-label">联系电话</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.phone }}</el-col>
            </el-row>
            <el-row class="info-row">
              <el-col :span="4" class="info-label">身份证号码</el-col>
              <el-col :span="20" class="info-value">{{ currentEmployee.id_number }}</el-col>
            </el-row>
            <el-row class="info-row">
              <el-col :span="4" class="info-label">户口所在地</el-col>
              <el-col :span="20" class="info-value">{{ currentEmployee.household_address }}</el-col>
            </el-row>
            <el-row class="info-row">
              <el-col :span="4" class="info-label">紧急联系人</el-col>
              <el-col :span="4" class="info-value">{{ currentEmployee.emergency_contact }}</el-col>
              <el-col :span="4" class="info-label">紧急联系电话</el-col>
              <el-col :span="12" class="info-value">{{ currentEmployee.emergency_phone }}</el-col>
            </el-row>
            <el-row class="info-row">
              <el-col :span="4" class="info-label">获得证书</el-col>
              <el-col :span="20" class="info-value">
                <span v-if="employeeCertificates.length">
                  <span v-for="(cert, idx) in employeeCertificates" :key="cert.id">
                    《{{ cert.name }}》<span v-if="idx !== employeeCertificates.length - 1">、</span>
                  </span>
                </span>
                <span v-else>无</span>
              </el-col>
            </el-row>
            <el-row class="info-row">
              <el-col :span="4" class="info-label">获奖情况</el-col>
              <el-col :span="20" class="info-value">
                <div style="white-space: pre-wrap;">{{ currentEmployee.awards }}</div>
              </el-col>
            </el-row>
            <el-row class="info-row not-center">
              <el-col :span="24" class="info-label" style="text-align: center; background-color: #F5F7FA; border-right: none;">个人专业技能</el-col>
            </el-row>
            <el-row class="info-row not-center">
              <el-col :span="24" class="info-value" style="border-right: none;">
                <div class="rich-text-content" v-html="currentEmployee.skills || ''"></div>
              </el-col>
            </el-row>
            <el-row class="info-row not-center">
              <el-col :span="24" class="info-label" style="text-align: center; background-color: #F5F7FA; border-right: none;">参与银行业相关的项目、担任的职务及职责内容（按照日期由近至远填写）</el-col>
            </el-row>
            <el-row class="info-row not-center">
              <el-col :span="24" class="info-value" style="border-right: none;">
                <div class="project-cards">
                  <div v-for="project in projects" :key="project.id" class="project-card">
                    <div class="project-header">
                      <div class="project-main-info">
                        <span class="project-name">{{ project.name }}</span>
                        <span class="project-divider">|</span>
                        <span class="project-period">{{ project.start_date }} 至 {{ project.end_date }}</span>
                        <span class="project-divider">|</span>
                        <span class="project-client">{{ project.client_name }}</span>
                        <span class="project-divider">|</span>
                        <span class="project-role">{{ project.role }}</span>
          </div>
        </div>
                    <div class="project-content">
                      <div v-if="project.description" class="project-desc">
                        <span class="label">项目描述：</span>
                        <span class="value">{{ project.description }}</span>
                      </div>
                      <div v-if="project.responsibilities" class="project-resp">
                        <span class="label">主要职责：</span>
                        <span class="value">{{ project.responsibilities }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
            <el-row class="info-row not-center">
              <el-col :span="24" class="info-label" style="text-align: center; background-color: #F5F7FA; border-right: none;">工作经历（按照日期由近至远填写）</el-col>
            </el-row>
            <el-row class="info-row not-center">
              <el-col :span="24" class="info-value" style="border-right: none;">
                <div class="work-cards">
                  <div v-for="work in workExperiences" :key="work.id" class="work-card">
                    <div class="work-header">
                      <div class="work-main-info">
                        <span class="work-company">{{ work.company }}</span>
                        <span class="work-divider">|</span>
                        <span class="work-department">{{ work.department }}</span>
                        <span class="work-divider">|</span>
                        <span class="work-period">{{ work.start_date }} 至 {{ work.end_date || '（今）' }}</span>
                        <span class="work-divider">|</span>
                        <span class="work-position">{{ work.position }}</span>
                      </div>
                    </div>
                    <div class="work-content">
                      <div v-if="work.description" class="work-desc">
                        <span class="label">工作描述：</span>
                        <span class="value">{{ work.description }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 工作经历 -->
        <div class="resume-section" v-if="false">
          <div class="section-title">工作经历</div>
          <el-table 
            :data="workExperiences" 
            style="width: 100%"
            :fit="true"
            size="small"
            height="400"
          >
            <el-table-column prop="company" label="公司名称" min-width="150" />
            <el-table-column prop="department" label="所在部门" min-width="120" />
            <el-table-column prop="position" label="职位" min-width="120" />
            <el-table-column prop="start_date" label="开始日期" min-width="100" />
            <el-table-column label="结束日期" min-width="100">
              <template #default="scope">
                {{ scope.row.end_date || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="description" label="工作描述" min-width="200" />
            <el-table-column prop="reference" label="证明人" min-width="100" />
            <el-table-column prop="reference_phone" label="证明人电话" min-width="120" />
          </el-table>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showExportDialog = false">取消</el-button>
          <el-button type="primary" @click="doExport">导出</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="showDetailsDialog"
      title="简历详情"
      width="70%"
      @open="currentEmployee.value && loadEmployeeContracts(currentEmployee.value.id)"
    >
      <el-tabs v-model="activeTab" @tab-click="handleDetailsTabClick">
        <!-- 基本信息标签页 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form
            :model="currentEmployee"
            label-width="120px"
            disabled
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="姓名">
                  <el-input v-model="currentEmployee.name" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别">
                  <DictRadio v-model="currentEmployee.gender" type="GENDER" :disabled="true" />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 入职时间 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="编号">
                  <el-input v-model="currentEmployee.number" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="入职时间">
                  <el-date-picker
                    v-model="currentEmployee.entry_time"
                    type="date"
                    placeholder=""
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 出生年月 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="出生年月">
                  <el-date-picker
                    v-model="currentEmployee.birth_date"
                    type="date"
                    placeholder=""
                    format="YYYY.MM"
                    value-format="YYYY.MM"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="年龄">
                  <el-input :model-value="calculateAge(currentEmployee.birth_date)" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="民族">
                  <el-select v-model="currentEmployee.ethnicity" placeholder="" disabled style="width: 100%">
                    <el-option v-for="item in ethnicityOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="籍贯">
                  <el-input v-model="currentEmployee.native_place" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="出生地">
                  <el-input v-model="currentEmployee.birth_place" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="政治面貌">
                  <DictRadio v-model="currentEmployee.political_status" type="POLITICAL_STATUS" :disabled="true" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="婚姻状况">
                  <DictRadio v-model="currentEmployee.marital_status" type="MARITAL_STATUS" :disabled="true" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="健康状况">
                  <el-input v-model="currentEmployee.health_status" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="毕业院校">
                  <el-input v-model="currentEmployee.school" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="专业">
                  <el-input v-model="currentEmployee.major" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="学历">
                  <el-select v-model="currentEmployee.degree" placeholder="" disabled>
                    <el-option v-for="item in degreeOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="学位">
                  <el-select v-model="currentEmployee.academic_degree" placeholder="" disabled>
                    <el-option v-for="item in academicDegreeOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 毕业时间 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="毕业时间">
                  <el-date-picker
                    v-model="currentEmployee.graduation_date"
                    type="date"
                    placeholder=""
                    format="YYYY.MM"
                    value-format="YYYY.MM"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="外语水平">
                  <el-select
                    v-model="currentEmployee.language_level"
                    placeholder=""
                    multiple
                    disabled
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in languageLevelOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="职称">
                  <el-input v-model="currentEmployee.title" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="岗位工作时间">
                  <el-date-picker
                    v-model="currentEmployee.position_start_date"
                    type="date"
                    placeholder=""
                    format="YYYY.MM"
                    value-format="YYYY.MM"
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="工作年限">
                  <el-input :model-value="calculateWorkYears(currentEmployee.graduation_date)" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="岗位相关工作年限">
                  <el-input :model-value="calculatePositionYears(currentEmployee.position_start_date)" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            
            <!-- 现任职务 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="部门">
                  <el-input v-model="currentEmployee.department" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="现任职务">
                  <el-input v-model="currentEmployee.position" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="现居住地址">
                  <el-input v-model="currentEmployee.current_address" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话">
                  <el-input v-model="currentEmployee.phone" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮箱">
                  <el-input v-model="currentEmployee.email" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号码">
                  <el-input v-model="currentEmployee.id_number" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="户口所在地">
                  <el-input v-model="currentEmployee.household_address" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="紧急联系人">
                  <el-input v-model="currentEmployee.emergency_contact" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="紧急联系电话">
                  <el-input v-model="currentEmployee.emergency_phone" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="获奖情况">
                  <el-input type="textarea" v-model="currentEmployee.awards" :rows="3" disabled />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>

        <!-- 教育背景标签页 -->
        <el-tab-pane label="教育背景" name="education">
          <div v-if="showDialog">
            <div class="tab-header">
              <el-button type="primary" @click="handleAddEducation">添加教育背景</el-button>
            </div>
            <el-table
              :data="educations"
              style="width: 100%"
              :fit="true"
              size="small"
              v-loading="educationLoading"
            >
              <el-table-column prop="degree" label="学历" min-width="80" />
              <el-table-column prop="major" label="专业" min-width="120" />
              <el-table-column prop="school" label="毕业院校" min-width="150" />
              <el-table-column prop="graduation_date" label="毕业时间" min-width="120">
                <template #default="scope">
                  {{ formatDate(scope.row.graduation_date) }}
                </template>
              </el-table-column>
              <el-table-column prop="degree_type" label="学历性质" min-width="100" />
              <el-table-column prop="is_double_certificate" label="是否双证" min-width="80">
                <template #default="scope">
                  <el-tag :type="scope.row.is_double_certificate ? 'success' : 'info'">
                    {{ scope.row.is_double_certificate ? '是' : '否' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="220" fixed="right">
                <template #default="scope">
                  <el-button size="small" type="warning" @click="handleViewEducation(scope.row)">查看</el-button>
                  <el-button size="small" type="primary" @click="handleEditEducation(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="handleDeleteEducation(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination" style="margin-top: 10px; text-align: right;">
              <el-pagination
                v-model:current-page="educationPage"
                v-model:page-size="educationPageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next"
                :total="educationTotal"
                @size-change="handleEducationSizeChange"
                @current-change="handleEducationPageChange"
              />
            </div>
            <el-dialog v-model="showEducationDialog" :title="educationDialogTitle" width="50%" :destroy-on-close="true">
              <el-form :model="educationForm" label-width="120px">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="学历" prop="degree">
                      <el-select v-model="educationForm.degree">
                        <el-option label="本科" value="本科" />
                        <el-option label="硕士" value="硕士" />
                        <el-option label="博士" value="博士" />
                        <el-option label="大专" value="大专" />
                        <el-option label="中专" value="中专" />
                        <el-option label="高中" value="高中" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="专业" prop="major">
                      <el-input v-model="educationForm.major" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="毕业院校" prop="school">
                      <el-input v-model="educationForm.school" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="毕业时间" prop="graduation_date">
                      <el-date-picker v-model="educationForm.graduation_date" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="学历性质" prop="degree_type">
                      <el-select v-model="educationForm.degree_type">
                        <el-option label="全日制" value="全日制" />
                        <el-option label="自考" value="自考" />
                        <el-option label="成教" value="成教" />
                        <el-option label="国开" value="国开" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="是否双证" prop="is_double_certificate">
                      <el-radio-group v-model="educationForm.is_double_certificate">
                        <el-radio-button :label="true">是</el-radio-button>
                        <el-radio-button :label="false">否</el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="showEducationDialog = false">取消</el-button>
                  <el-button type="primary" @click="handleSaveEducation">保存</el-button>
                </span>
              </template>
            </el-dialog>
          </div>
          <div v-else-if="showDetailsDialog">
            <el-table
              :data="educations"
              style="width: 100%"
              :fit="true"
              size="small"
              v-loading="educationLoading"
            >
              <el-table-column prop="degree" label="学历" min-width="80" />
              <el-table-column prop="major" label="专业" min-width="120" />
              <el-table-column prop="school" label="毕业院校" min-width="150" />
              <el-table-column prop="graduation_date" label="毕业时间" min-width="120">
                <template #default="scope">
                  {{ formatDate(scope.row.graduation_date) }}
                </template>
              </el-table-column>
              <el-table-column prop="degree_type" label="学历性质" min-width="100" />
              <el-table-column prop="is_double_certificate" label="是否双证" min-width="80">
                <template #default="scope">
                  <el-tag :type="scope.row.is_double_certificate ? 'success' : 'info'">
                    {{ scope.row.is_double_certificate ? '是' : '否' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" fixed="right">
                <template #default="scope">
                  <el-button size="small" type="warning" @click="handleViewEducation(scope.row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination" style="margin-top: 10px; text-align: right;">
              <el-pagination
                v-model:current-page="educationPage"
                v-model:page-size="educationPageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next"
                :total="educationTotal"
                @size-change="handleEducationSizeChange"
                @current-change="handleEducationPageChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <!-- 获得证书标签页 -->
        <el-tab-pane label="获得证书" name="certificates">
          <div v-if="showDialog">
            <div class="tab-header">
              <el-button type="primary" @click="() => { certDialogMode = 'add'; currentCertificate = null; showCertDialog = true }">添加证书</el-button>
            </div>
            <div class="table-container" style="height: 100%; display: flex; flex-direction: column; overflow-x: auto;">
              <el-table
                :data="employeeCertificates"
                style="width: 100%; min-width: 1200px;"
                v-loading="certLoading"
                :fit="true"
                size="small"
              >
                <el-table-column prop="name" label="证书名称" min-width="180" show-overflow-tooltip />
                <el-table-column prop="certificate_no" label="证书编号" min-width="150" show-overflow-tooltip />
                <el-table-column prop="level" label="证书级别" width="120" show-overflow-tooltip />
                <el-table-column prop="issuing_org" label="发证机构" min-width="180" show-overflow-tooltip />
                <el-table-column prop="issue_date" label="获得日期" width="120">
                  <template #default="scope">
                    {{ formatDate(scope.row.issue_date) }}
                  </template>
                </el-table-column>
                <el-table-column prop="expiry_date" label="有效期" width="120">
                  <template #default="scope">
                    {{ formatDate(scope.row.expiry_date) }}
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="备注说明" min-width="150" show-overflow-tooltip />
                <el-table-column label="操作" width="220" fixed="right">
                  <template #default="scope">
                    <el-button size="small" type="warning" @click="handleCertView(scope.row)">查看</el-button>
                    <el-button size="small" type="primary" @click="handleCertEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleCertDelete(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="pagination" style="flex-shrink: 0;">
                <el-pagination
                  v-model:current-page="certPage"
                  v-model:page-size="certPageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next"
                  :total="certTotal"
                  @size-change="handleCertSizeChange"
                  @current-change="handleCertCurrentChange"
                />
              </div>
            </div>
            <el-dialog v-model="showCertDialog" title="证书详情" width="80%" style="max-width: 1200px" :destroy-on-close="true" class="certificate-dialog">
              <div class="dialog-content">
                <certificate-form
                  v-if="showCertDialog"
                  :mode="certDialogMode"
                  :certificate="currentCertificate"
                  :employee-id="currentEmployeeId"
                  @close="showCertDialog = false"
                />
              </div>
            </el-dialog>
          </div>
          <div v-else-if="showDetailsDialog">
            <div class="table-container" style="height: 100%; display: flex; flex-direction: column; overflow-x: auto;">
              <el-table
                :data="employeeCertificates"
                style="width: 100%; min-width: 1200px;"
                v-loading="certLoading"
                :fit="true"
                size="small"
              >
                <el-table-column prop="name" label="证书名称" min-width="180" show-overflow-tooltip />
                <el-table-column prop="certificate_no" label="证书编号" min-width="150" show-overflow-tooltip />
                <el-table-column prop="level" label="证书级别" width="120" show-overflow-tooltip />
                <el-table-column prop="issuing_org" label="发证机构" min-width="180" show-overflow-tooltip />
                <el-table-column prop="issue_date" label="获得日期" width="120">
                  <template #default="scope">
                    {{ formatDate(scope.row.issue_date) }}
                  </template>
                </el-table-column>
                <el-table-column prop="expiry_date" label="有效期" width="120">
                  <template #default="scope">
                    {{ formatDate(scope.row.expiry_date) }}
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="备注说明" min-width="150" show-overflow-tooltip />
                <el-table-column label="操作" width="100" fixed="right">
                  <template #default="scope">
                    <el-button size="small" type="warning" @click="handleCertView(scope.row)">查看</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="pagination" style="flex-shrink: 0;">
                <el-pagination
                  v-model:current-page="certPage"
                  v-model:page-size="certPageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next"
                  :total="certTotal"
                  @size-change="handleCertSizeChange"
                  @current-change="handleCertCurrentChange"
                />
              </div>
            </div>
            <el-dialog v-model="showCertDialog" title="证书详情" width="80%" style="max-width: 1200px" :destroy-on-close="true" class="certificate-dialog">
              <div class="dialog-content">
                <certificate-form
                  v-if="showCertDialog"
                  :mode="certDialogMode"
                  :certificate="currentCertificate"
                  :employee-id="currentEmployeeId"
                  @close="showCertDialog = false"
                />
              </div>
            </el-dialog>
          </div>
        </el-tab-pane>

        <!-- 个人专业技能标签页 -->
        <el-tab-pane label="个人专业技能" name="skills">
          <div style="border: 1px solid #ccc" v-if="activeEditTab === 'skills'">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
            />
            <Editor
              style="height: 400px; overflow-y: hidden;"
              v-model="form.skills"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="handleEditorCreated"
              @onDestroyed="handleEditorDestroyed"
              @onChange="handleEditorChange"
            />
          </div>
        </el-tab-pane>

        <!-- 项目经验标签页 -->
        <el-tab-pane label="项目经验" name="projects">
          <div class="tab-header">
            <el-button type="primary" @click="showProjectDialog = true">添加项目经验</el-button>
          </div>
          <el-table 
            :data="projects" 
            style="width: 100%"
            :fit="true"
            size="small"
          >
            <el-table-column prop="name" label="项目名称" min-width="120" />
            <el-table-column prop="client_name" label="客户名称" min-width="120" />
            <el-table-column prop="role" label="担任角色" min-width="100" />
            <el-table-column prop="start_date" label="开始日期" min-width="100" />
            <el-table-column prop="end_date" label="结束日期" min-width="100" />
            <el-table-column prop="responsibilities" label="主要职责" min-width="200" />
            <el-table-column label="操作" width="300" fixed="right">
              <template #default="scope">
                <el-button size="small" type="warning" @click="handleViewProject(scope.row)">查看</el-button>
                <el-button size="small" type="primary" @click="handleEditProject(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDeleteProject(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination" style="margin-top: 10px; text-align: right;">
            <el-pagination
              v-model:current-page="projectsPage"
              v-model:page-size="projectsPageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next"
              :total="projectsTotal"
              @size-change="handleProjectsSizeChange"
              @current-change="handleProjectsPageChange"
            />
          </div>
        </el-tab-pane>

        <!-- 工作经历标签页 -->
        <el-tab-pane label="工作经历" name="workExperience">
          <div class="tab-header">
            <el-button type="primary" @click="handleAddWorkExperience">添加工作经历</el-button>
          </div>
          <el-table 
            :data="workExperiences" 
            style="width: 100%"
            :fit="true"
            size="small"
          >
            <el-table-column prop="company" label="公司名称" min-width="150" />
            <el-table-column prop="department" label="所在部门" min-width="120" />
            <el-table-column prop="position" label="职位" min-width="120" />
            <el-table-column prop="start_date" label="开始日期" min-width="100" />
            <el-table-column label="结束日期" min-width="100">
              <template #default="scope">
                {{ scope.row.end_date || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="description" label="工作描述" min-width="200" />
            <el-table-column prop="reference" label="证明人" min-width="100" />
            <el-table-column prop="reference_phone" label="证明人电话" min-width="120" />
            <el-table-column label="操作" width="300" fixed="right">
              <template #default="scope">
                <el-button size="small" type="warning" @click="handleViewWorkExperience(scope.row)">查看</el-button>
                <el-button size="small" type="primary" @click="handleEditWorkExperience(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDeleteWorkExperience(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination" style="margin-top: 10px; text-align: right;">
            <el-pagination
              v-model:current-page="workPage"
              v-model:page-size="workPageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next"
              :total="workTotal"
              @size-change="handleWorkSizeChange"
              @current-change="handleWorkPageChange"
            />
          </div>
        </el-tab-pane>

        <!-- 培训经历标签页 -->
        <el-tab-pane label="培训经历" name="trainingExperience">
          <div v-if="showDialog" class="tab-header" style="margin-bottom: 10px;">
            <el-button type="primary" @click="() => { trainingDialogTitle = '添加培训经历'; trainingForm = { course_name: '', organization: '', start_date: '', end_date: '', certificate: '' }; showTrainingDialog = true }">添加培训经历</el-button>
          </div>
          <el-table :data="trainingExperiences" style="width: 100%" :fit="true" size="small">
            <el-table-column prop="course_name" label="培训课程名称" min-width="150" />
            <el-table-column prop="organization" label="培训机构" min-width="120" />
            <el-table-column label="培训时间" min-width="180">
              <template #default="scope">
                {{ scope.row.start_date }} 至 {{ scope.row.end_date }}
              </template>
            </el-table-column>
            <el-table-column prop="certificate" label="培训证书" min-width="120" />
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="scope">
                <el-button size="small" type="warning" @click="handleViewTraining(scope.row)">查看</el-button>
                <el-button v-if="showDialog" size="small" type="primary" @click="handleEditTraining(scope.row)">编辑</el-button>
                <el-button v-if="showDialog" size="small" type="danger" @click="handleDeleteTraining(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 培训经历编辑/新增弹窗 -->
          <el-dialog
            v-model="showTrainingDialog"
            :title="trainingDialogTitle"
            :width="'80%'"
            style="max-width: 1200px"
            :destroy-on-close="true"
          >
            <el-form :model="trainingForm" ref="trainingFormRef" label-width="120px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="培训课程名称" prop="course_name">
                    <el-input v-model="trainingForm.course_name" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="培训机构" prop="organization">
                    <el-input v-model="trainingForm.organization" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="开始日期" prop="start_date">
                    <el-date-picker v-model="trainingForm.start_date" type="date" placeholder="选择开始日期" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结束日期" prop="end_date">
                    <el-date-picker v-model="trainingForm.end_date" type="date" placeholder="选择结束日期" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="培训证书" prop="certificate">
                    <el-input v-model="trainingForm.certificate" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="描述" prop="description">
                    <el-input v-model="trainingForm.description" type="textarea" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="showTrainingDialog = false">取消</el-button>
                <el-button type="primary" @click="submitTrainingForm">保存</el-button>
              </span>
            </template>
          </el-dialog>
          <!-- 培训经历只读详情弹窗 -->
          <el-dialog v-model="showTrainingViewDialog" title="培训经历详情" width="80%" :style="{maxWidth: '1200px'}">
            <el-form label-width="120px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="培训课程名称">
                    <el-input :model-value="currentTrainingView.course_name" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="培训机构">
                    <el-input :model-value="currentTrainingView.organization" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="培训时间">
                    <el-input :model-value="(currentTrainingView.start_date || '') + ' 至 ' + (currentTrainingView.end_date || '')" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="培训证书">
                    <el-input :model-value="currentTrainingView.certificate" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item v-if="currentTrainingView.description" label="描述">
                    <el-input type="textarea" :model-value="currentTrainingView.description" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="showTrainingViewDialog = false">关闭</el-button>
              </span>
            </template>
          </el-dialog>
        </el-tab-pane>

        <!-- 合同信息标签页 -->
        <el-tab-pane label="合同信息" name="contracts">
          <div v-if="showDialog" class="tab-header" style="margin-bottom: 10px;">
            <el-button type="primary" @click="handleAddContract">添加合同</el-button>
          </div>
          <el-table :data="employeeContracts" style="width: 100%; min-width: 1200px;" :fit="true" size="small">
            <el-table-column prop="contract_number" label="合同编号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="contract_type" label="合同类型" min-width="100">
              <template #default="scope">
                <el-tag :type="scope.row.contract_type === '劳动合同' ? 'success' : (scope.row.contract_type === '劳务合同' ? 'warning' : 'info')">
                  {{ scope.row.contract_type }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="contract_party" label="合同主体" min-width="120" show-overflow-tooltip />
            <el-table-column prop="start_date" label="签订日期" min-width="120">
              <template #default="scope">
                {{ formatDate(scope.row.start_date) }}
              </template>
            </el-table-column>
            <el-table-column prop="end_date" label="到期日期" min-width="120">
              <template #default="scope">
                {{ formatDate(scope.row.end_date) }}
              </template>
            </el-table-column>
            <el-table-column label="合同年限" min-width="100">
              <template #default="scope">
                {{ calculateContractYears(scope.row.start_date, scope.row.end_date) }}
              </template>
            </el-table-column>
            <el-table-column prop="is_expired" label="合同状态" min-width="100">
              <template #default="scope">
                <el-tag :type="scope.row.is_expired ? 'danger' : 'success'">
                  {{ scope.row.is_expired ? '已到期' : '未到期' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="scope">
                <el-button size="small" type="warning" @click="handleViewContract(scope.row)">查看</el-button>
                <el-button v-if="showDialog" size="small" type="primary" @click="handleEditContract(scope.row)">编辑</el-button>
                <el-button v-if="showDialog" size="small" type="danger" @click="handleDeleteContract(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 档案资料标签页 -->
        <el-tab-pane label="档案资料" name="attachments">
          <div v-if="showDialog">
            <div class="contract-attachment-card attachment-card-with-label">
              <span class="attachment-card-label">附件列表</span>
              <AttachmentList
                v-if="activeEditTab === 'attachments'"
                :attachments="attachments"
                :loading="loadingAttachments"
                :readonly="false"
                module="employees"
                :moduleId="currentEmployee.id"
                :download-function="handleDownloadAttachment"
                :delete-function="handleDeleteAttachment"
                :preview-function="handlePreviewAttachment"
                @refresh="loadAttachments"
                @add-attachment="showAttachmentUploader = true"
              />
              <el-dialog v-model="showAttachmentUploader" title="上传附件" width="500px" destroy-on-close @closed="handleUploadDialogClosed">
                <AttachmentUploader
                  module="employees"
                  :moduleId="currentEmployee.id"
                  @upload-success="handleUploadSuccess"
                />
              </el-dialog>
            </div>
          </div>
          <div v-else-if="showDetailsDialog">
            <div class="contract-attachment-card attachment-card-with-label">
              <span class="attachment-card-label">附件列表</span>
              <AttachmentList
                v-if="activeEditTab === 'attachments'"
                :attachments="attachments"
                :loading="loadingAttachments"
                :readonly="true"
                module="employees"
                :moduleId="currentEmployee.id"
                :download-function="handleDownloadAttachment"
                :preview-function="handlePreviewAttachment"
              />
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="奖惩记录" name="rewardPunishment">
          <RewardPunishmentTable
            v-if="activeEditTab === 'rewardPunishment'"
            :employee-id="form.id || null"
            :readonly="!showDialog"
            :key="'edit-' + (form.id || '') + '-' + showDialog"
          />
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDetailsDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 项目经验对话框 -->
    <el-dialog
      v-model="showProjectDialog"
      :title="projectDialogTitle"
      width="50%"
    >
      <el-form :model="projectForm" :rules="projectRules" ref="projectFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="name">
              <el-input v-model="projectForm.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="client_name">
              <el-input v-model="projectForm.client_name" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="担任角色" prop="role">
              <el-input v-model="projectForm.role" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="start_date">
              <el-date-picker
                v-model="projectForm.start_date"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="end_date">
              <el-date-picker
                v-model="projectForm.end_date"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目成果" prop="achievements">
              <el-input type="textarea" v-model="projectForm.achievements" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目描述" prop="description">
              <el-input type="textarea" v-model="projectForm.description" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="主要职责" prop="responsibilities">
              <el-input type="textarea" v-model="projectForm.responsibilities" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showProjectDialog = false">取消</el-button>
          <el-button type="primary" @click="submitProjectForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 工作经历对话框 -->
    <el-dialog
      v-model="showWorkExperienceDialog"
      :title="workExperienceDialogTitle"
      width="50%"
    >
      <el-form :model="workExperienceForm" :rules="workExperienceRules" ref="workExperienceFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司名称" prop="company">
              <el-input v-model="workExperienceForm.company" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在部门" prop="department">
              <el-input v-model="workExperienceForm.department" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="workExperienceForm.position" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="start_date">
              <el-date-picker
                v-model="workExperienceForm.start_date"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="结束日期" prop="end_date">
              <el-date-picker
                v-model="workExperienceForm.end_date"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证明人" prop="reference">
              <el-input v-model="workExperienceForm.reference" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="证明人电话" prop="reference_phone">
              <el-input v-model="workExperienceForm.reference_phone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工作描述" prop="description">
              <el-input type="textarea" v-model="workExperienceForm.description" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="离职原因" prop="reason_for_leaving">
              <el-input type="textarea" v-model="workExperienceForm.reason_for_leaving" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showWorkExperienceDialog = false">取消</el-button>
          <el-button type="primary" @click="submitWorkExperienceForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 证书对话框 -->
    <el-dialog
      v-model="showCertificateDialog"
      :title="certificateDialogTitle"
      width="50%"
    >
      <el-form :model="certificateForm" :rules="certificateRules" ref="certificateFormRef" label-width="120px">
        <el-form-item label="证书名称" prop="name">
          <el-input v-model="certificateForm.name" />
        </el-form-item>
        <el-form-item label="证书编号" prop="certificate_number">
          <el-input v-model="certificateForm.certificate_number" />
        </el-form-item>
        <el-form-item label="发证机构" prop="issuing_organization">
          <el-input v-model="certificateForm.issuing_organization" />
        </el-form-item>
        <el-form-item label="发证日期" prop="issue_date">
          <el-date-picker
            v-model="certificateForm.issue_date"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="有效期" prop="expiry_date">
          <el-date-picker
            v-model="certificateForm.expiry_date"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="证书扫描件" prop="scan_file">
          <el-upload
            class="upload-demo"
            action="/api/upload"
            :on-success="handleCertificateUploadSuccess"
            :on-error="handleCertificateUploadError"
            :before-upload="beforeCertificateUpload"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过2MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCertificateDialog = false">取消</el-button>
          <el-button type="primary" @click="submitCertificateForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 项目经验查看对话框 -->
    <el-dialog
      v-model="showProjectViewDialog"
      title="项目经验详情"
      width="50%"
    >
      <el-form label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称">
              <el-input :model-value="currentProject.name" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称">
              <el-input :model-value="currentProject.client_name" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="担任角色">
              <el-input :model-value="currentProject.role" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始日期">
              <el-input :model-value="currentProject.start_date" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="结束日期">
              <el-input :model-value="currentProject.end_date" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目成果">
              <el-input type="textarea" :rows="2" :model-value="currentProject.achievements" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目描述">
              <el-input type="textarea" :rows="2" :model-value="currentProject.description" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="主要职责">
              <el-input type="textarea" :rows="2" :model-value="currentProject.responsibilities" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showProjectViewDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 工作经历查看对话框 -->
    <el-dialog
      v-model="showWorkExperienceViewDialog"
      title="工作经历详情"
      width="50%"
    >
      <el-form label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司名称">
              <el-input :model-value="currentWorkExperience.company" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在部门">
              <el-input :model-value="currentWorkExperience.department" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位">
              <el-input :model-value="currentWorkExperience.position" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始日期">
              <el-input :model-value="currentWorkExperience.start_date" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="结束日期">
              <el-input :model-value="currentWorkExperience.end_date || '-'" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证明人">
              <el-input :model-value="currentWorkExperience.reference" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="证明人电话">
              <el-input :model-value="currentWorkExperience.reference_phone" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工作描述">
              <el-input type="textarea" :rows="2" :model-value="currentWorkExperience.description" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="离职原因">
              <el-input type="textarea" :rows="2" :model-value="currentWorkExperience.reason_for_leaving" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showWorkExperienceViewDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 合同表单弹窗 -->
    <el-dialog :title="contractDialogTitle" v-model="showContractDialog" width="80%" style="max-width: 1200px">
      <el-form :model="contractForm" :rules="contractFormRules" ref="contractFormRef" label-width="120px" style="padding:24px 32px 0 32px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contract_number">
              <el-input v-model="contractForm.contract_number" :disabled="contractDialogMode === 'view'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同类型" prop="contract_type">
              <el-select v-model="contractForm.contract_type" :disabled="contractDialogMode === 'view'">
                <el-option label="劳动合同" value="劳动合同" />
                <el-option label="劳务合同" value="劳务合同" />
                <el-option label="实习协议" value="实习协议" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同主体" prop="contract_party">
              <el-input v-model="contractForm.contract_party" :disabled="contractDialogMode === 'view'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签订日期" prop="start_date">
              <el-date-picker v-model="contractForm.start_date" type="date" placeholder="选择签订日期" style="width: 100%" :disabled="contractDialogMode === 'view'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="到期日期" prop="end_date">
              <el-date-picker v-model="contractForm.end_date" type="date" placeholder="选择到期日期" style="width: 100%" :disabled="contractDialogMode === 'view'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同状态" v-if="contractDialogMode === 'view'">
              <el-input :value="contractForm.is_expired ? '已到期' : '未到期'" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 附件列表区域（保持原样） -->
      <div v-if="contractDialogMode !== 'add' && contractForm.id" class="contract-attachment-card attachment-card-with-label">
        <span class="attachment-card-label">附件列表</span>
        <AttachmentList
          v-if="contractDialogMode === 'edit'"
          :attachments="contractAttachments"
          :loading="contractAttachmentsLoading"
          :readonly="false"
          :download-function="handleDownloadContractAttachment"
          :delete-function="handleDeleteContractAttachment"
          :preview-function="handlePreviewContractAttachment"
          @refresh="loadContractAttachments"
          @add-attachment="showContractAttachmentUploader = true"
        />
        <AttachmentList
          v-else
          :attachments="contractAttachments"
          :loading="contractAttachmentsLoading"
          :readonly="true"
          :download-function="handleDownloadContractAttachment"
          :preview-function="handlePreviewContractAttachment"
        />
        <el-dialog v-model="showContractAttachmentUploader" title="上传附件" width="500px" destroy-on-close>
          <AttachmentUploader
            module="contracts"
            :moduleId="contractForm.id"
            @upload-success="handleContractAttachmentUploadSuccess"
          />
        </el-dialog>
      </div>
      <template #footer>
        <span class="dialog-footer" style="display:block;text-align:right;">
          <el-button @click="showContractDialog = false">取消</el-button>
          <el-button v-if="contractDialogMode !== 'view'" type="primary" @click="submitContractForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="showEducationViewDialog" title="教育背景详情" width="50%">
      <el-form label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学历">
              <el-input :model-value="currentEducationView.degree" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业">
              <el-input :model-value="currentEducationView.major" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="毕业院校">
              <el-input :model-value="currentEducationView.school" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毕业时间">
              <el-input :model-value="currentEducationView.graduation_date" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学历性质">
              <el-input :model-value="currentEducationView.degree_type" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否双证">
              <el-tag :type="currentEducationView.is_double_certificate ? 'success' : 'info'">
                {{ currentEducationView.is_double_certificate ? '是' : '否' }}
              </el-tag>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEducationViewDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="showEducationDialog" :title="educationDialogTitle" width="50%" :destroy-on-close="true">
      <el-form :model="educationForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学历" prop="degree">
              <el-select v-model="educationForm.degree">
                <el-option label="本科" value="本科" />
                <el-option label="硕士" value="硕士" />
                <el-option label="博士" value="博士" />
                <el-option label="大专" value="大专" />
                <el-option label="中专" value="中专" />
                <el-option label="高中" value="高中" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" prop="major">
              <el-input v-model="educationForm.major" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="毕业院校" prop="school">
              <el-input v-model="educationForm.school" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毕业时间" prop="graduation_date">
              <el-date-picker v-model="educationForm.graduation_date" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学历性质" prop="degree_type">
              <el-select v-model="educationForm.degree_type">
                <el-option label="全日制" value="全日制" />
                <el-option label="自考" value="自考" />
                <el-option label="成教" value="成教" />
                <el-option label="国开" value="国开" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否双证" prop="is_double_certificate">
              <el-radio-group v-model="educationForm.is_double_certificate">
                <el-radio-button :label="true">是</el-radio-button>
                <el-radio-button :label="false">否</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEducationDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSaveEducation">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="showEducationDialog" :title="educationDialogTitle" width="50%" :destroy-on-close="true">
      <el-form :model="educationForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学历" prop="degree">
              <el-select v-model="educationForm.degree">
                <el-option label="本科" value="本科" />
                <el-option label="硕士" value="硕士" />
                <el-option label="博士" value="博士" />
                <el-option label="大专" value="大专" />
                <el-option label="中专" value="中专" />
                <el-option label="高中" value="高中" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" prop="major">
              <el-input v-model="educationForm.major" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="毕业院校" prop="school">
              <el-input v-model="educationForm.school" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毕业时间" prop="graduation_date">
              <el-date-picker v-model="educationForm.graduation_date" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学历性质" prop="degree_type">
              <el-select v-model="educationForm.degree_type">
                <el-option label="全日制" value="全日制" />
                <el-option label="自考" value="自考" />
                <el-option label="成教" value="成教" />
                <el-option label="国开" value="国开" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否双证" prop="is_double_certificate">
              <el-radio-group v-model="educationForm.is_double_certificate">
                <el-radio-button :label="true">是</el-radio-button>
                <el-radio-button :label="false">否</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEducationDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSaveEducation">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed, onUnmounted, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { Plus, Download, View, Edit, Delete } from '@element-plus/icons-vue'
import { employeeAPI as employeeApi, projectAPI as projectApi, workExperienceAPI as workExperienceApi, certificateAPI as certificateApi } from '../api'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import AttachmentUploader from '../components/AttachmentUploader.vue'
import AttachmentList from '../components/AttachmentList.vue'
import CertificateForm from './Certificate/CertificateForm.vue'
import { contractInfoAPI, contractAPI } from '@/api/index'
import trainingExperienceApi from '@/api/trainingExperienceApi'
import { educationAPI } from '../api'
import RewardPunishmentTable from '../components/RewardPunishmentTable.vue'
import DictRadio from '../components/DictRadio.vue'
import { getDictItemsByCode } from '../api/dict'

export default {
  name: 'Employees',
  components: {
    Search,
    Editor,
    Toolbar,
    AttachmentUploader,
    AttachmentList,
    CertificateForm,
    RewardPunishmentTable,
    Plus,
    Download,
    View,
    Edit,
    Delete,
    DictRadio
  },
  setup() {
    const formRef = ref(null)
    const employees = ref([])
    const searchQuery = ref('')
    const showDialog = ref(false)
    const dialogTitle = computed(() => {
      return currentId.value ? '编辑简历' : '添加简历'
    })
    const showExportDialog = ref(false)
    const exportForm = ref({
      templateId: '',
      employeeId: null
    })
    const templates = ref([])
    const currentId = ref(null)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const form = ref({
      name: '',
      number: '',
      entry_time: '',
      department: '',
      gender: '',
      birth_date: '',
      ethnicity: '',
      native_place: '',
      birth_place: '',
      political_status: '',
      marital_status: '',
      health_status: '',
      phone: '',
      email: '',
      school: '',
      major: '',
      degree: '',
      graduation_date: '',
      language_level: [],
      title: '',
      position_start_date: '',
      current_company: '',
      position: '',
      contract_period: null,
      contract_period_start: '',
      contract_period_end: '',
      current_address: '',
      id_number: '',
      household_address: '',
      emergency_contact: '',
      emergency_phone: '',
      awards: '',
      skills: ''
    })
    const showDetailsDialog = ref(false)
    const currentEmployee = ref({})
    const activeTab = ref('basic')
    const activeEditTab = ref('basic')
    const projects = ref([])
    const workExperiences = ref([])
    const certificates = ref([])
    
    // 证书相关
    const showCertificateDialog = ref(false)
    const certificateDialogTitle = ref('添加证书')
    const certificateFormRef = ref(null)
    const certificateForm = ref({
      name: '',
      certificate_number: '',
      issuing_organization: '',
      issue_date: '',
      expiry_date: '',
      scan_file: null
    })
    const certificateRules = {
      name: [{ required: true, message: '请输入证书名称', trigger: 'blur' }],
      certificate_number: [{ required: true, message: '请输入证书编号', trigger: 'blur' }],
      issuing_organization: [{ required: true, message: '请输入发证机构', trigger: 'blur' }],
      issue_date: [{ required: true, message: '请选择发证日期', trigger: 'change' }],
      expiry_date: [{ required: true, message: '请选择有效期', trigger: 'change' }]
    }

    // 项目经验相关
    const showProjectDialog = ref(false)
    const projectDialogTitle = ref('添加项目经验')
    const projectFormRef = ref(null)
    const projectForm = ref({
      name: '',
      client_name: '',
      role: '',
      start_date: '',
      end_date: '',
      description: '',
      responsibilities: '',
      achievements: ''
    })
    const projectRules = {
      name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
      client_name: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
      role: [{ required: true, message: '请输入担任角色', trigger: 'blur' }],
      start_date: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
      end_date: [{ required: true, message: '请选择结束日期', trigger: 'change' }]
    }

    // 工作经历相关
    const showWorkExperienceDialog = ref(false)
    const workExperienceDialogTitle = ref('添加工作经历')
    const workExperienceFormRef = ref(null)
    const workExperienceForm = ref({
      company: '',
      department: '',
      position: '',
      start_date: '',
      end_date: '',
      description: '',
      reason_for_leaving: '',
      reference: '',
      reference_phone: ''
    })
    const workExperienceRules = {
      company: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
      department: [{ required: true, message: '请输入所在部门', trigger: 'blur' }],
      position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
      start_date: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
      end_date: [{ required: false, message: '请选择结束日期', trigger: 'change' }],
      reference_phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ]
    }

    const rules = {
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      number: [
         { required: true, message: '请输入编号', trigger: 'blur' }
      ],
      entry_time: [
         { required: true, message: '请选择入职时间', trigger: 'change' }
      ],
      department: [
         { required: true, message: '请输入部门', trigger: 'blur' }
      ],
      gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
      ],
      birth_date: [
        { required: true, message: '请选择出生日期', trigger: 'change' }
      ],
      ethnicity: [
        { required: true, message: '请选择民族', trigger: 'change' }
      ],
      native_place: [
        { required: true, message: '请输入籍贯', trigger: 'blur' }
      ],
      birth_place: [
        { required: true, message: '请输入出生地', trigger: 'blur' }
      ],
      political_status: [
        { required: true, message: '请选择政治面貌', trigger: 'change' }
      ],
      marital_status: [
        { required: true, message: '请选择婚姻状况', trigger: 'change' }
      ],
      health_status: [
        { required: true, message: '请输入健康状况', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
      ],
      school: [
        { required: true, message: '请输入毕业院校', trigger: 'blur' }
      ],
      major: [
        { required: true, message: '请输入专业', trigger: 'blur' }
      ],
      degree: [
        { required: true, message: '请选择学历', trigger: 'change' }
      ],
      academic_degree: [
        { required: true, message: '请选择学位', trigger: 'change' }
      ],
      graduation_date: [
        { required: true, message: '请选择毕业时间', trigger: 'change' }
      ],
      language_level: [
        { required: true, message: '请选择外语水平', trigger: 'change' }
      ],
      title: [
        { required: true, message: '请输入职称', trigger: 'blur' }
      ],
      position_start_date: [
        { required: true, message: '请选择岗位工作时间', trigger: 'change' }
      ],
      position: [
        { required: true, message: '请输入现任职务', trigger: 'blur' }
      ],
      current_address: [
        { required: true, message: '请输入现居住地址', trigger: 'blur' }
      ],
      id_number: [
        { required: true, message: '请输入身份证号码', trigger: 'blur' },
        { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
      ],
      household_address: [
        { required: true, message: '请输入户口所在地', trigger: 'blur' }
      ],
      emergency_contact: [
        { required: true, message: '请输入紧急联系人', trigger: 'blur' }
      ],
      emergency_phone: [
        { required: true, message: '请输入紧急联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      awards: [
        { max: 1000, message: '获奖情况不能超过1000个字符', trigger: 'blur' }
      ],
      skills: [
        { max: 2000, message: '专业技能描述不能超过2000个字符', trigger: 'blur' }
      ]
    }

    const loadEmployees = async () => {
      try {
        const response = await employeeApi.getAll(currentPage.value, pageSize.value)
        employees.value = response.data.data
        total.value = response.data.total
      } catch (error) {
        ElMessage.error('加载简历列表失败')
      }
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      loadEmployees()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadEmployees()
    }

    const filteredEmployees = computed(() => {
      if (!searchQuery.value) return employees.value
      return employees.value.filter(employee => 
        employee.name.toLowerCase().includes(searchQuery.value.toLowerCase())
      )
    })

    const handleSearch = () => {
      // 搜索逻辑已通过计算属性实现
    }

    // 延迟加载标签页数据状态
    const loadedTabs = ref({
      basic: true,
      certificates: false,
      skills: false,
      projects: false,
      workExperience: false,
      attachments: false,
      trainingExperience: false,
      education: false
    })

    // 重置延迟加载状态
    const resetLoadedTabs = () => {
      loadedTabs.value = {
        basic: true,
        certificates: false,
        skills: false,
        projects: false,
        workExperience: false,
        attachments: false,
        trainingExperience: false,
        education: false
      }
    }

    // 延迟加载标签页数据
    const handleTabChange = async (tab) => {
      const tabName = typeof tab === 'string' ? tab : tab.name
      if (loadedTabs.value[tabName]) return
      switch (tabName) {
        case 'certificates':
          await loadEmployeeCertificates(currentEmployeeId.value)
          break
        case 'projects':
          await loadProjects()
          break
        case 'workExperience':
          await loadWorkExperiences()
          break
        case 'trainingExperience':
          await loadTrainingExperiences()
          break
        case 'education':
          await loadEducations()
          break
        case 'skills':
          nextTick(() => {
            if (editorRef.value) {
              try {
                editorRef.value.setHtml(form.value.skills || '')
              } catch (error) {
                console.error('设置编辑器内容失败:', error)
              }
            }
          })
          break
      }
      loadedTabs.value[tabName] = true
    }

    // 监听标签页切换，支持代码切换
    watch(activeEditTab, (newTab) => {
      handleTabChange(newTab)
    })

    // 新增：监听详情弹窗的tab切换，延迟加载数据
    watch(activeTab, (newTab) => {
      handleTabChange(newTab)
    })

    // 新增：监听currentEmployee变化，重置延迟加载tab状态
    watch(currentEmployee, () => {
      resetLoadedTabs()
    })

    // 在弹窗打开时重置延迟加载状态
    const handleEdit = async (row) => {
      try {
        activeEditTab.value = 'basic'
        resetLoadedTabs()
        currentEmployeeId.value = row.id
        const response = await employeeApi.getById(row.id)
        currentId.value = row.id
        currentEmployee.value = { ...response.data }
        dialogTitle.value = '编辑简历'
        form.value = { ...response.data }
        // 设置合同起止日期
        if (form.value.contract_period_start && form.value.contract_period_end) {
          form.value.contract_period = [form.value.contract_period_start, form.value.contract_period_end]
        } else {
          form.value.contract_period = null
        }
        // 只加载基本信息，其他tab延迟加载
        showDialog.value = true
        nextTick(() => {
          if (editorRef.value) {
            editorRef.value.setHtml(form.value.skills || '')
          }
        })
      } catch (error) {
        ElMessage.error('获取简历信息失败')
      }
    }

    const handleDelete = (row) => {
      ElMessageBox.confirm('确定要删除该简历吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await employeeApi.delete(row.id)
          ElMessage.success('删除成功')
          loadEmployees()
        } catch (error) {
          ElMessage.error('删除失败')
        }
      }).catch(() => {
        // 用户点击取消按钮，不做任何处理
      })
    }

    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // 获取富文本的 HTML 内容
            if (editorRef.value) {
              form.value.skills = editorRef.value.getHtml()
            }

            // 处理日期格式
            const formData = { ...form.value }
            if (formData.birth_date) {
              formData.birth_date = new Date(formData.birth_date).toISOString().split('T')[0]
            }
            if (formData.graduation_date) {
              formData.graduation_date = new Date(formData.graduation_date).toISOString().split('T')[0]
            }
            if (formData.position_start_date) {
              formData.position_start_date = new Date(formData.position_start_date).toISOString().split('T')[0]
            }
            if (formData.contract_period_start) {
              formData.contract_period_start = new Date(formData.contract_period_start).toISOString().split('T')[0]
            }
            if (formData.contract_period_end) {
              formData.contract_period_end = new Date(formData.contract_period_end).toISOString().split('T')[0]
            }
            if (formData.entry_time) {
              formData.entry_time = new Date(formData.entry_time).toISOString().split('T')[0]
            }

            if (currentId.value) {
              await employeeApi.update(currentId.value, formData)
              ElMessage.success('更新成功')
            } else {
              await employeeApi.create(formData)
              ElMessage.success('添加成功')
            }
            showDialog.value = false
            loadEmployees()
          } catch (error) {
            ElMessage.error(currentId.value ? '更新失败' : '添加失败')
            console.error('保存失败:', error)
          }
        }
      })
    }

    const handleViewDetails = async (row) => {
      try {
        activeEditTab.value = 'basic'
        resetLoadedTabs()
        currentEmployeeId.value = row.id
        const response = await employeeApi.getById(row.id)
        currentEmployee.value = { ...response.data }

        // 确保学历和学位选项加载完毕
        if (degreeOptions.value.length === 0) {
          await getDictItemsByCode('DEGREE').then(res => {
            degreeOptions.value = res.data
          })
        }
        if (academicDegreeOptions.value.length === 0) {
          await getDictItemsByCode('ACADEMIC_DEGREE').then(res => {
            academicDegreeOptions.value = res.data
          })
        }

        // 先打开弹窗
        showDetailsDialog.value = true
        // 立即加载合同信息，避免第一次打开无数据
        loadEmployeeContracts(currentEmployee.value.id)
        // 新增：弹窗打开后自动加载当前激活tab的数据
        nextTick(() => {
          handleDetailsTabClick({ name: activeTab.value })
        })
      } catch (error) {
        ElMessage.error('获取简历详情失败')
      }
    }

    const handleExport = async (row) => {
      try {
        const response = await employeeApi.getById(row.id)
        currentEmployee.value = { ...response.data }
        exportForm.value.employeeId = row.id
        // 设置默认模板为农信
        const defaultTemplate = templates.value.find(t => t.name === '农信')
        if (defaultTemplate) {
          exportForm.value.templateId = defaultTemplate.id
        }
        // 加载相关数据
        await Promise.all([
          loadProjects(),
          loadWorkExperiences(),
          loadEmployeeContracts(row.id),
          loadEmployeeCertificates(row.id) // 新增：导出时主动加载证书
        ])
        showExportDialog.value = true
      } catch (error) {
        ElMessage.error('获取简历信息失败')
      }
    }

    const doExport = async () => {
      if (!exportForm.value.templateId) {
        ElMessage.warning('请选择模板')
        return
      }

      try {
        const response = await employeeApi.exportResume(exportForm.value.employeeId, exportForm.value.templateId)
        const employee = employees.value.find(e => e.id === exportForm.value.employeeId)
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', `简历_${employee.name}.docx`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        ElMessage.success('导出成功')
        showExportDialog.value = false
      } catch (error) {
        ElMessage.error('导出失败')
      }
    }

    const handleContractPeriodChange = (value) => {
      if (value && value.length === 2) {
        form.value.contract_period_start = value[0]
        form.value.contract_period_end = value[1]
      } else {
        form.value.contract_period_start = ''
        form.value.contract_period_end = ''
        form.value.contract_period = null
      }
    }

    // 计算工作年限
    const workYears = computed(() => {
      if (!form.value.graduation_date) return 0
      const graduationDate = new Date(form.value.graduation_date)
      const now = new Date()
      const years = now.getFullYear() - graduationDate.getFullYear()
      const months = now.getMonth() - graduationDate.getMonth()
      return Math.floor(years + months / 12)
    })

    // 计算岗位相关工作年限
    const positionYears = computed(() => {
      if (!form.value.position_start_date) return 0
      const startDate = new Date(form.value.position_start_date)
      const now = new Date()
      const years = now.getFullYear() - startDate.getFullYear()
      const months = now.getMonth() - startDate.getMonth()
      return Math.floor(years + months / 12)
    })

    const calculateWorkYears = (graduationDate) => {
      if (!graduationDate) return 0
      const graduation = new Date(graduationDate)
      const now = new Date()
      const years = now.getFullYear() - graduation.getFullYear()
      const months = now.getMonth() - graduation.getMonth()
      return Math.floor(years + months / 12)
    }

    const calculatePositionYears = (positionStartDate) => {
      if (!positionStartDate) return 0
      const startDate = new Date(positionStartDate)
      const now = new Date()
      const years = now.getFullYear() - startDate.getFullYear()
      const months = now.getMonth() - startDate.getMonth()
      return Math.floor(years + months / 12)
    }

    // 加载证书
    const loadCertificates = async () => {
      if (!currentEmployee.value?.id) return
      try {
        const response = await certificateApi.getAll(currentEmployee.value.id)
        certificates.value = response.data
      } catch (error) {
        ElMessage.error('加载证书失败')
      }
    }

    // 加载项目经验
    const projectsPage = ref(1)
    const projectsPageSize = ref(10)
    const projectsTotal = ref(0)
    const workPage = ref(1)
    const workPageSize = ref(10)
    const workTotal = ref(0)

    const loadProjects = async () => {
      if (!currentEmployee.value?.id) return
      try {
        const response = await projectApi.getAll(currentEmployee.value.id, { page: projectsPage.value, per_page: projectsPageSize.value })
        projects.value = response.data.data || response.data
        projectsTotal.value = response.data.total || response.data.length || 0
      } catch (error) {
        ElMessage.error('加载项目经验失败')
      }
    }
    const handleProjectsPageChange = (val) => {
      projectsPage.value = val
      loadProjects()
    }
    const handleProjectsSizeChange = (val) => {
      projectsPageSize.value = val
      projectsPage.value = 1
      loadProjects()
    }

    // 加载工作经历
    const loadWorkExperiences = async () => {
      if (!currentEmployee.value?.id) return
      try {
        const response = await workExperienceApi.getAll(currentEmployee.value.id, { page: workPage.value, per_page: workPageSize.value })
        workExperiences.value = response.data.data || response.data
        workTotal.value = response.data.total || response.data.length || 0
      } catch (error) {
        ElMessage.error('加载工作经历失败')
      }
    }
    const handleWorkPageChange = (val) => {
      workPage.value = val
      loadWorkExperiences()
    }
    const handleWorkSizeChange = (val) => {
      workPageSize.value = val
      workPage.value = 1
      loadWorkExperiences()
    }

    // 处理项目经验编辑
    const handleEditProject = (row) => {
      projectDialogTitle.value = '编辑项目经验'
      projectForm.value = { ...row }
      showProjectDialog.value = true
    }

    // 处理项目经验删除
    const handleDeleteProject = (row) => {
      ElMessageBox.confirm('确定要删除该项目经验吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await projectApi.delete(currentEmployee.value.id, row.id)
          ElMessage.success('删除成功')
          loadProjects()
        } catch (error) {
          ElMessage.error('删除失败')
        }
      }).catch(() => {
        // 用户点击取消按钮，不做任何处理
      })
    }

    // 提交项目经验表单
    const submitProjectForm = async () => {
      console.log('submitProjectForm called')
      console.log('projectFormRef.value:', projectFormRef.value)
      if (!projectFormRef.value) return
      try {
        const valid = await projectFormRef.value.validate()
        console.log('校验结果 valid:', valid)
        console.log('当前表单数据:', projectForm.value)
        if (valid) {
          if (projectForm.value.id) {
            await projectApi.update(currentEmployee.value.id, projectForm.value.id, projectForm.value)
            ElMessage.success('更新成功')
          } else {
            await projectApi.create(currentEmployee.value.id, projectForm.value)
            ElMessage.success('添加成功')
          }
          showProjectDialog.value = false
          loadProjects()
        }
      } catch (error) {
        // 校验未通过会抛出异常
        console.log('表单校验未通过', error)
      }
    }

    // 处理工作经历编辑
    const handleEditWorkExperience = (row) => {
      workExperienceDialogTitle.value = '编辑工作经历'
      workExperienceForm.value = { ...row }
      showWorkExperienceDialog.value = true
    }

    // 新增：处理工作经历新增
    const handleAddWorkExperience = () => {
      workExperienceDialogTitle.value = '添加工作经历'
      workExperienceForm.value = {
        company: '',
        department: '',
        position: '',
        start_date: '',
        end_date: '',
        description: '',
        reason_for_leaving: '',
        reference: '',
        reference_phone: ''
      }
      showWorkExperienceDialog.value = true
      nextTick(() => {
        if (workExperienceFormRef.value) {
          workExperienceFormRef.value.clearValidate && workExperienceFormRef.value.clearValidate()
        }
      })
    }

    // 处理工作经历删除
    const handleDeleteWorkExperience = (row) => {
      ElMessageBox.confirm('确定要删除该工作经历吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await workExperienceApi.delete(currentEmployee.value.id, row.id)
          ElMessage.success('删除成功')
          loadWorkExperiences()
        } catch (error) {
          ElMessage.error('删除失败')
        }
      }).catch(() => {
        // 用户点击取消按钮，不做任何处理
      })
    }

    // 提交工作经历表单
    const submitWorkExperienceForm = async () => {
      if (!workExperienceFormRef.value) return
      
      await workExperienceFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (workExperienceForm.value.id) {
              await workExperienceApi.update(currentEmployee.value.id, workExperienceForm.value.id, workExperienceForm.value)
              ElMessage.success('更新成功')
            } else {
              await workExperienceApi.create(currentEmployee.value.id, workExperienceForm.value)
              ElMessage.success('添加成功')
            }
            showWorkExperienceDialog.value = false
            loadWorkExperiences()
          } catch (error) {
            ElMessage.error(workExperienceForm.value.id ? '更新失败' : '添加失败')
          }
        }
      })
    }

    // 处理证书编辑
    const handleEditCertificate = (row) => {
      certificateDialogTitle.value = '编辑证书'
      certificateForm.value = { ...row }
      showCertificateDialog.value = true
    }

    // 处理证书删除
    const handleDeleteCertificate = (row) => {
      ElMessageBox.confirm('确定要删除该证书吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await certificateApi.delete(currentEmployee.value.id, row.id)
          ElMessage.success('删除成功')
          loadCertificates()
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
    }

    // 提交证书表单
    const submitCertificateForm = async () => {
      if (!certificateFormRef.value) return
      
      await certificateFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (certificateForm.value.id) {
              await certificateApi.update(currentEmployee.value.id, certificateForm.value.id, certificateForm.value)
              ElMessage.success('更新成功')
            } else {
              await certificateApi.create(currentEmployee.value.id, certificateForm.value)
              ElMessage.success('添加成功')
            }
            showCertificateDialog.value = false
            loadCertificates()
          } catch (error) {
            ElMessage.error(certificateForm.value.id ? '更新失败' : '添加失败')
          }
        }
      })
    }

    // 处理证书上传
    const handleCertificateUploadSuccess = (response) => {
      certificateForm.value.scan_file = response.url
      ElMessage.success('上传成功')
    }

    const handleCertificateUploadError = () => {
      ElMessage.error('上传失败')
    }

    const beforeCertificateUpload = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        ElMessage.error('只能上传JPG/PNG格式的图片!')
      }
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过2MB!')
      }
      return isJPG && isLt2M
    }

    const handleEditorCreated = (editor) => {
      editorRef.value = editor
      // 禁用拖拽上传
      editor.disable()
      editor.enable()
      // 如果是编辑模式，设置初始内容
      nextTick(() => {
        if (form.value.skills) {
          try {
            editor.setHtml(form.value.skills)
          } catch (error) {
            console.error('设置编辑器内容失败:', error)
          }
        }
      })
    }

    const handleEditorChange = (editor) => {
      try {
        form.value.skills = editor.getHtml()
      } catch (error) {
        console.error('获取编辑器内容失败:', error)
      }
    }

    const handleEditorDestroyed = () => {
      editorRef.value = null
    }

    const tableHeight = ref('400px')

    // 处理表格大小变化
    const handleTableResize = () => {
      // 使用 requestAnimationFrame 来优化性能
      requestAnimationFrame(() => {
        const container = document.querySelector('.table-container')
        if (container) {
          const containerHeight = container.getBoundingClientRect().height
          tableHeight.value = `${containerHeight - 20}px`  // 减去一些边距
        }
      })
    }

    // 监听窗口大小变化
    onMounted(() => {
      loadEmployees()
      // 添加 ResizeObserver 错误处理
      const resizeObserverErrHandler = (err) => {
        if (err.message.includes('ResizeObserver loop completed with undelivered notifications')) {
          // 忽略这个特定的错误
          err.stopImmediatePropagation()
          return
        }
        console.error(err)
      }
      window.addEventListener('error', resizeObserverErrHandler)

      // 保存处理函数引用以便在组件卸载时移除
      window._resizeObserverErrHandler = resizeObserverErrHandler

      window.addEventListener('resize', handleTableResize)
      // 初始化表格高度
      handleTableResize()

      calcCertificateTableHeight()
      window.addEventListener('resize', calcCertificateTableHeight)

      getDictItemsByCode('DEGREE').then(res => {
        degreeOptions.value = res.data
      })
      getDictItemsByCode('ACADEMIC_DEGREE').then(res => {
        academicDegreeOptions.value = res.data
      })
      // 新增：加载外语水平选项
      getDictItemsByCode('LANGUAGE_LEVEL').then(res => {
        languageLevelOptions.value = res.data
      })
      // 新增：加载民族选项
      getDictItemsByCode('ETHNICITY').then(res => {
        ethnicityOptions.value = res.data
      })
    })

    onUnmounted(() => {
      if (window._resizeObserverErrHandler) {
        window.removeEventListener('error', window._resizeObserverErrHandler)
        delete window._resizeObserverErrHandler
      }
      // 确保编辑器实例被正确销毁
      const editor = editorRef.value
      if (editor) {
          editor.destroy()
        }
        editorRef.value = null

      window.removeEventListener('resize', handleTableResize)
      window.removeEventListener('resize', calcCertificateTableHeight)
      languageLevelOptions
      // 新增：民族选项
      ethnicityOptions
    })

    const showProjectViewDialog = ref(false)
    const showWorkExperienceViewDialog = ref(false)
    const currentProject = ref({})
    const currentWorkExperience = ref({})

    // 处理项目经验查看
    const handleViewProject = (row) => {
      currentProject.value = { ...row }
      showProjectViewDialog.value = true
    }

    // 处理工作经历查看
    const handleViewWorkExperience = (row) => {
      currentWorkExperience.value = { ...row }
      showWorkExperienceViewDialog.value = true
    }

    // 计算年龄
    const calculateAge = (birthDate) => {
      if (!birthDate) return ''
      const birth = new Date(birthDate)
      const now = new Date()
      let age = now.getFullYear() - birth.getFullYear()
      const monthDiff = now.getMonth() - birth.getMonth()
      
      if (monthDiff < 0 || (monthDiff === 0 && now.getDate() < birth.getDate())) {
        age--
      }
      
      return age
    }

    // 附件相关
    const showAttachmentUploader = ref(false)
    const attachments = ref([])
    const loadingAttachments = ref(false)

    // 加载附件列表
    const loadAttachments = async () => {
      if (!currentEmployee.value?.id) return
      loadingAttachments.value = true
      try {
        const response = await employeeApi.getAttachments(currentEmployee.value.id)
        attachments.value = response.data
      } catch (error) {
        ElMessage.error('加载附件列表失败')
      } finally {
        loadingAttachments.value = false
      }
    }

    // 处理附件上传
    const handleUploadAttachment = async (employeeId, file, description) => {
      try {
        await employeeApi.addAttachment(employeeId, file, description)
        ElMessage.success('上传成功')
      } catch (error) {
        ElMessage.error('上传附件失败')
        console.error('上传附件失败:', error)
        throw error
      }
    }

    // 处理上传成功
    const handleUploadSuccess = async () => {
      showAttachmentUploader.value = false
      await loadAttachments()
    }

    // 处理附件下载
    const handleDownloadAttachment = async (attachmentId) => {
      try {
        const response = await employeeApi.download(attachmentId)
        const blob = new Blob([response.data])
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = response.headers['content-disposition']?.split('filename=')[1] || 'attachment'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      } catch (error) {
        ElMessage.error('下载文件失败')
        console.error('下载文件失败:', error)
      }
    }

    // 处理附件删除
    const handleDeleteAttachment = async (attachmentId) => {
      try {
        await employeeApi.deleteAttachment(currentEmployee.value.id, attachmentId)
        ElMessage.success('删除成功')
        await loadAttachments()
      } catch (error) {
        ElMessage.error('删除附件失败')
        console.error('删除附件失败:', error)
      }
    }

    // 处理附件预览
    const handlePreviewAttachment = (attachmentId) => {
      return employeeApi.getPreviewUrl(attachmentId)
    }

    // 关闭上传对话框
    const handleUploadDialogClosed = () => {
      loadAttachments()
    }

    // 格式化文件大小
    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }

    const employeeCertificates = ref([])
    const certLoading = ref(false)
    const certPage = ref(1)
    const certPageSize = ref(10)
    const certTotal = ref(0)
    const showCertDialog = ref(false)
    const currentCertificate = ref(null)
    const certDialogMode = ref('view')
    const currentEmployeeId = ref(null)

    function formatDate(date) {
      if (!date) return ''
      return date.split('T')[0]
    }

    async function loadEmployeeCertificates(employeeId) {
      if (!employeeId) {
        employeeCertificates.value = []
        certTotal.value = 0
        return
      }
      certLoading.value = true
      try {
        // employee_id 作为 params 传递，保证只查当前员工证书
        const res = await certificateApi.getAll(certPage.value, certPageSize.value, { employee_id: employeeId })
        employeeCertificates.value = res.data.items || []
        certTotal.value = res.data.total || 0
        currentEmployeeId.value = employeeId
      } catch (e) {
        employeeCertificates.value = []
        certTotal.value = 0
      } finally {
        certLoading.value = false
      }
    }

    function handleCertView(row) {
      currentCertificate.value = row
      certDialogMode.value = 'view'
      showCertDialog.value = true
    }
    function handleCertEdit(row) {
      certificateApi.getById(row.id).then(res => {
        const data = res.data
        if (data.issuing_organization && !data.issuing_org) {
          data.issuing_org = data.issuing_organization
        }
        currentCertificate.value = data
        certDialogMode.value = 'edit'
        showCertDialog.value = true
      })
    }
    async function handleCertDelete(row) {
      ElMessageBox.confirm('确定要删除该证书吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await certificateApi.delete(row.id)
          ElMessage.success('删除成功')
          loadEmployeeCertificates(currentEmployeeId.value)
        } catch (error) {
          ElMessage.error('删除失败')
        }
      }).catch(() => {
        // 用户点击取消，不做处理
      })
    }
    function handleCertSizeChange(size) {
      certPageSize.value = size
      loadEmployeeCertificates(currentEmployeeId.value)
    }
    function handleCertCurrentChange(page) {
      certPage.value = page
      loadEmployeeCertificates(currentEmployeeId.value)
    }
    // 在handleEdit、handleViewDetails等弹窗打开时调用loadEmployeeCertificates(row.id)

    // 富文本编辑器相关
    const editorRef = ref(null)
    const toolbarConfig = {
      excludeKeys: [
        'uploadVideo',
        'insertTable',
        'codeBlock',
        'todo',
        'group-video',
        'group-image',
        'insertImage',
        'uploadImage',
        'emotion',
        'fullScreen'
      ]
    }
    const editorConfig = {
      placeholder: '请输入专业技能描述',
      MENU_CONF: {
        fontSize: {
          title: '字号',
          default: '14px'
        },
        lineHeight: {
          title: '行高',
          default: '1.5'
        },
        uploadImage: {
          server: '',
          fieldName: 'file',
          maxFileSize: 2 * 1024 * 1024,
          maxNumberOfFiles: 1,
          allowedFileTypes: ['image/*'],
          meta: {},
          metaWithUrl: false,
          withCredentials: false,
          timeout: 5 * 1000
        }
      },
      autoFocus: false,
      scroll: true,
      maxLength: 2000,
      customAlert: (info, type) => {
        if (type === 'error') {
          ElMessage.error(info)
        } else {
          ElMessage.info(info)
        }
      }
    }

    // 证书表格自适应高度
    const certificateTableHeight = ref(400)
    function calcCertificateTableHeight() {
      // 计算窗口高度-顶部偏移-分页等（可根据实际页面微调）
      const offset = 340 // 头部、tab、margin等高度
      certificateTableHeight.value = Math.max(window.innerHeight - offset, 200)
    }

    const employeeContracts = ref([])
    const contractsLoading = ref(false)
    // 计算最新合同
    const latestContract = computed(() => {
      if (!employeeContracts.value.length) return null
      // 按end_date降序，取第一份
      return [...employeeContracts.value].sort((a, b) => new Date(b.end_date) - new Date(a.end_date))[0]
    })

    async function loadEmployeeContracts(employeeId) {
      contractsLoading.value = true
      try {
        const res = await contractInfoAPI.getByEmployeeId(employeeId)
        employeeContracts.value = res.data || []
      } catch (e) {
        employeeContracts.value = []
      } finally {
        contractsLoading.value = false
      }
    }

    function calculateContractYears(start, end) {
      if (!start || !end) return ''
      const s = new Date(start)
      const e = new Date(end)
      const years = e.getFullYear() - s.getFullYear()
      const months = e.getMonth() - s.getMonth()
      return years + (months > 0 ? `年${months}个月` : '年')
    }

    const handleTabClick = (tab) => {
      if (tab.paneName === 'contracts' && currentEmployee.value && currentEmployee.value.id) {
        loadEmployeeContracts(currentEmployee.value.id)
      }
    }

    const showContractDialog = ref(false)
    const contractDialogTitle = ref('')
    const contractDialogMode = ref('add') // add/edit/view
    const contractForm = ref({
      contract_number: '',
      contract_type: '',
      contract_party: '',
      start_date: '',
      end_date: ''
    })
    const contractFormRef = ref(null)
    const contractFormRules = {
      contract_number: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
      contract_type: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
      contract_party: [{ required: true, message: '请输入合同主体', trigger: 'blur' }],
      start_date: [{ required: true, message: '请选择签订日期', trigger: 'change' }],
      end_date: [{ required: true, message: '请选择到期日期', trigger: 'change' }]
    }
    function handleAddContract() {
      contractDialogTitle.value = '新增合同'
      contractDialogMode.value = 'add'
      contractForm.value = {
        contract_number: '',
        contract_type: '',
        contract_party: '',
        start_date: '',
        end_date: ''
      }
      showContractDialog.value = true
    }
    function handleEditContract(row) {
      contractDialogTitle.value = '编辑合同'
      contractDialogMode.value = 'edit'
      contractForm.value = { ...row }
      showContractDialog.value = true
    }
    function handleViewContract(row) {
      contractDialogTitle.value = '查看合同'
      contractDialogMode.value = 'view'
      contractForm.value = { ...row }
      showContractDialog.value = true
      // 不再手动调用 loadContractAttachments()
    }
    async function handleDeleteContract(row) {
      ElMessageBox.confirm('确定要删除该合同吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await contractAPI.delete(row.id)
          ElMessage.success('删除成功')
          loadEmployeeContracts(currentEmployee.value.id)
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
    }
    async function submitContractForm() {
      if (!contractFormRef.value) return
      await contractFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (contractDialogMode.value === 'add') {
              await contractAPI.create({
                ...contractForm.value,
                employee_id: currentEmployee.value.id
              })
              ElMessage.success('新增成功')
            } else if (contractDialogMode.value === 'edit') {
              await contractAPI.update(contractForm.value.id, {
                ...contractForm.value,
                employee_id: currentEmployee.value.id
              })
              ElMessage.success('更新成功')
            }
            showContractDialog.value = false
            loadEmployeeContracts(currentEmployee.value.id)
          } catch (error) {
            ElMessage.error(contractDialogMode.value === 'add' ? '新增失败' : '更新失败')
          }
        }
      })
    }

    const contractAttachments = ref([])
    const contractAttachmentsLoading = ref(false)
    async function loadContractAttachments() {
      if (!contractForm.value.id) {
        contractAttachments.value = []
        return
      }
      contractAttachmentsLoading.value = true
      try {
        const res = await contractAPI.getAttachments(contractForm.value.id)
        contractAttachments.value = res.data || []
      } catch (e) {
        contractAttachments.value = []
      } finally {
        contractAttachmentsLoading.value = false
      }
    }
    async function handleUploadContractAttachment(contractId, file, description) {
      try {
        await contractAPI.addAttachment(contractId, file, description)
        ElMessage.success('上传成功')
        loadContractAttachments()
      } catch (e) {
        ElMessage.error('上传失败')
        throw e
      }
    }
    async function handleDeleteContractAttachment(attachmentId) {
      try {
        await contractAPI.deleteAttachment(contractForm.value.id, attachmentId)
        ElMessage.success('删除成功')
        loadContractAttachments()
      } catch (e) {
        ElMessage.error('删除失败')
      }
    }
    function handleDownloadContractAttachment(attachmentId) {
      contractAPI.download(attachmentId).then(res => {
        const blob = new Blob([res.data])
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = res.headers['content-disposition']?.split('filename=')[1] || 'attachment'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      })
    }
    function handlePreviewContractAttachment(attachmentId) {
      return contractAPI.getPreviewUrl(attachmentId)
    }
    // 弹窗打开时加载附件
    watch([showContractDialog, () => contractForm.value.id], ([visible, id]) => {
      if (visible && id) {
        loadContractAttachments()
      }
    })

    const showContractAttachmentUploader = ref(false)
    function handleContractAttachmentUploadSuccess() {
      showContractAttachmentUploader.value = false
      loadContractAttachments()
    }

    const trainingExperiences = ref([])
    const showTrainingDialog = ref(false)
    const trainingDialogTitle = ref('添加培训经历')
    const trainingFormRef = ref(null)
    const trainingForm = ref({
      course_name: '',
      organization: '',
      start_date: '',
      end_date: '',
      certificate: ''
    })
    const currentTrainingId = ref(null)
    const showTrainingAttachments = ref(false)
    const showTrainingUploader = ref(false)
    const trainingAttachments = ref([])
    const loadingTrainingAttachments = ref(false)

    const loadTrainingExperiences = async () => {
      if (!currentEmployee.value?.id) return
      const res = await trainingExperienceApi.getAll(currentEmployee.value.id)
      trainingExperiences.value = Array.isArray(res.data) ? res.data : (res.data.data || [])
    }
    const handleEditTraining = (row) => {
      trainingDialogTitle.value = '编辑培训经历'
      trainingForm.value = { ...row }
      showTrainingDialog.value = true
      // 自动加载附件列表
      if (row.id) {
        loadTrainingAttachments(row.id)
      }
    }
    const handleDeleteTraining = async (row) => {
      await trainingExperienceApi.remove(row.id)
      loadTrainingExperiences()
    }
    const submitTrainingForm = async () => {
      if (trainingDialogTitle.value === '添加培训经历') {
        await trainingExperienceApi.add({ ...trainingForm.value, employee_id: currentEmployee.value.id })
      } else {
        await trainingExperienceApi.update(trainingForm.value.id, trainingForm.value)
      }
      showTrainingDialog.value = false
      loadTrainingExperiences()
    }
    const handleShowAttachments = (row) => {
      currentTrainingId.value = row.id
      loadTrainingAttachments(row.id)
      showTrainingAttachments.value = true
    }
    const loadTrainingAttachments = async (trainingId) => {
      loadingTrainingAttachments.value = true
      const res = await trainingExperienceApi.getAttachments(trainingId)
      trainingAttachments.value = res.data.data || []
      loadingTrainingAttachments.value = false
    }
    const handleDownloadTrainingAttachment = (id) => {
      window.open(`/api/attachments/download/${id}`)
    }
    // watch(currentEmployee, () => {
    //   loadTrainingExperiences()
    // })

    const handleUploadTrainingAttachment = async (trainingId, file, description) => {
      try {
        await trainingExperienceApi.addAttachment(trainingId, file, description)
        ElMessage.success('上传成功')
        loadTrainingAttachments(trainingId)
        showTrainingUploader.value = false
      } catch (error) {
        ElMessage.error('上传失败')
        throw error
      }
    }
    const handleDeleteTrainingAttachment = async (trainingId, attachmentId) => {
      try {
        await trainingExperienceApi.deleteAttachment(trainingId, attachmentId)
        loadTrainingAttachments(trainingId)
        ElMessage.success('删除成功')
      } catch (error) {
        ElMessage.error('删除失败')
      }
    }
    const handlePreviewTrainingAttachment = (attachmentId) => {
      return trainingExperienceApi.getPreviewUrl(attachmentId)
    }

    function handleDetailsTabClick(tab) {
      const tabName = typeof tab === 'string' ? tab : tab.name
      if (tabName === 'contracts' && currentEmployee.value && currentEmployee.value.id) {
        loadEmployeeContracts(currentEmployee.value.id)
      }
      // 可按需添加其他tab的延迟加载逻辑
    }

    const showTrainingViewDialog = ref(false)
    const currentTrainingView = ref({})
    function handleViewTraining(row) {
      currentTrainingView.value = { ...row }
      showTrainingViewDialog.value = true
    }

    const educations = ref([])
    const educationPage = ref(1)
    const educationPageSize = ref(10)
    const educationTotal = ref(0)
    const educationLoading = ref(false)

    const loadEducations = async () => {
      if (!currentEmployee.value?.id) return
      educationLoading.value = true
      try {
        const response = await educationAPI.getAll(currentEmployee.value.id, { page: educationPage.value, per_page: educationPageSize.value })
        educations.value = response.data.data || response.data
        educationTotal.value = response.data.total || response.data.length || 0
      } catch (error) {
        ElMessage.error('加载教育背景失败')
      } finally {
        educationLoading.value = false
      }
    }

    const handleEducationPageChange = (val) => {
      educationPage.value = val
      loadEducations()
    }
    const handleEducationSizeChange = (val) => {
      educationPageSize.value = val
      educationPage.value = 1
      loadEducations()
    }

    const showEducationDialog = ref(false)
    const educationDialogTitle = ref('编辑教育背景')
    const educationForm = ref({
      degree: '',
      major: '',
      school: '',
      graduation_date: '',
      degree_type: '',
      is_double_certificate: false
    })
    const showEducationViewDialog = ref(false)
    const currentEducationView = ref({})
    function handleViewEducation(row) {
      currentEducationView.value = { ...row }
      showEducationViewDialog.value = true
    }
    function handleEditEducation(row) {
      educationDialogTitle.value = '编辑教育背景'
      educationForm.value = { ...row }
      showEducationDialog.value = true
    }

    const handleDeleteEducation = (row) => {
      ElMessageBox.confirm('确定要删除该教育背景吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await educationAPI.delete(currentEmployee.value.id, row.id)
          ElMessage.success('删除成功')
          loadEducations()
        } catch (error) {
          ElMessage.error('删除失败')
        }
      }).catch(() => {
        // 用户点击取消，不做处理
      })
    }

    function handleAddEducation() {
      educationDialogTitle.value = '添加教育背景'
      educationForm.value = {
        degree: '',
        major: '',
        school: '',
        graduation_date: '',
        degree_type: '',
        is_double_certificate: false
      }
      showEducationDialog.value = true
    }

    const handleAddResume = () => {
      form.value = {
        name: '',
        number: '',
        entry_time: '',
        department: '',
        gender: '',
        birth_date: '',
        ethnicity: '',
        native_place: '',
        birth_place: '',
        political_status: '',
        marital_status: '',
        health_status: '',
        phone: '',
        email: '',
        school: '',
        major: '',
        degree: '',
        graduation_date: '',
        language_level: [],
        title: '',
        position_start_date: '',
        current_company: '',
        position: '',
        contract_period: null,
        contract_period_start: '',
        contract_period_end: '',
        current_address: '',
        id_number: '',
        household_address: '',
        emergency_contact: '',
        emergency_phone: '',
        awards: '',
        skills: ''
      }
      currentId.value = null
      activeEditTab.value = 'basic'
      showDialog.value = true
    }

    function handleMainDialogClose() {
      if (editorRef.value) {
        try {
          editorRef.value.destroy()
        } catch (e) { /* ignore error */ }
        editorRef.value = null
      }
    }

    const handleExportExcel = async () => {
      try {
        const res = await employeeApi.exportExcel()
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = '员工简历列表.xlsx'
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url)
      } catch (e) {
        window.$message?.error?.('导出失败，请稍后重试')
      }
    }

    const degreeOptions = ref([])
    const academicDegreeOptions = ref([])
    // 新增：外语水平选项
    const languageLevelOptions = ref([])

    // 新增：民族选项
    const ethnicityOptions = ref([])

    return {
      formRef,
      employees,
      searchQuery,
      showDialog,
      dialogTitle,
      showExportDialog,
      exportForm,
      templates,
      form,
      rules,
      handleEdit,
      handleDelete,
      handleViewDetails,
      handleExport,
      submitForm,
      doExport,
      filteredEmployees,
      handleSearch,
      showDetailsDialog,
      currentEmployee,
      handleContractPeriodChange,
      workYears,
      positionYears,
      calculateWorkYears,
      calculatePositionYears,
      calculateAge,
      currentPage,
      pageSize,
      total,
      handleSizeChange,
      handleCurrentChange,
      activeTab,
      activeEditTab,
      projects,
      workExperiences,
      certificates,
      showCertificateDialog,
      certificateDialogTitle,
      certificateForm,
      certificateRules,
      showProjectDialog,
      projectDialogTitle,
      projectForm,
      projectRules,
      showWorkExperienceDialog,
      workExperienceDialogTitle,
      workExperienceForm,
      workExperienceRules,
      handleEditProject,
      handleDeleteProject,
      submitProjectForm,
      handleEditWorkExperience,
      handleDeleteWorkExperience,
      submitWorkExperienceForm,
      loadCertificates,
      handleEditCertificate,
      handleDeleteCertificate,
      submitCertificateForm,
      handleCertificateUploadSuccess,
      handleCertificateUploadError,
      beforeCertificateUpload,
      handleTabChange,
      editorRef,
      toolbarConfig,
      editorConfig,
      handleEditorCreated,
      handleEditorChange,
      handleEditorDestroyed,
      showProjectViewDialog,
      showWorkExperienceViewDialog,
      currentProject,
      currentWorkExperience,
      handleViewProject,
      handleViewWorkExperience,
      tableHeight,
      handleTableResize,
      showAttachmentUploader,
      attachments,
      loadingAttachments,
      handleUploadAttachment,
      handleUploadSuccess,
      handleDownloadAttachment,
      handleDeleteAttachment,
      handlePreviewAttachment,
      handleUploadDialogClosed,
      formatFileSize,
      employeeCertificates,
      certLoading,
      certPage,
      certPageSize,
      certTotal,
      showCertDialog,
      currentCertificate,
      certDialogMode,
      currentEmployeeId,
      formatDate,
      loadEmployeeCertificates,
      handleCertView,
      handleCertEdit,
      handleCertDelete,
      handleCertSizeChange,
      handleCertCurrentChange,
      loadedTabs,
      resetLoadedTabs,
      certificateTableHeight,
      calcCertificateTableHeight,
      projectsPage,
      projectsPageSize,
      projectsTotal,
      workPage,
      workPageSize,
      workTotal,
      handleProjectsPageChange,
      handleProjectsSizeChange,
      handleWorkPageChange,
      handleWorkSizeChange,
      employeeContracts,
      contractsLoading,
      loadEmployeeContracts,
      calculateContractYears,
      handleTabClick,
      showContractDialog,
      contractDialogTitle,
      contractDialogMode,
      contractForm,
      contractFormRef,
      contractFormRules,
      handleAddContract,
      handleEditContract,
      handleViewContract,
      handleDeleteContract,
      submitContractForm,
      contractAttachments,
      contractAttachmentsLoading,
      loadContractAttachments,
      handleUploadContractAttachment,
      handleDeleteContractAttachment,
      handleDownloadContractAttachment,
      handlePreviewContractAttachment,
      showContractAttachmentUploader,
      handleContractAttachmentUploadSuccess,
      trainingExperiences,
      showTrainingDialog,
      trainingDialogTitle,
      trainingForm,
      trainingFormRef,
      currentTrainingId,
      showTrainingAttachments,
      showTrainingUploader,
      trainingAttachments,
      loadingTrainingAttachments,
      loadTrainingExperiences,
      handleEditTraining,
      handleDeleteTraining,
      submitTrainingForm,
      handleShowAttachments,
      handleDownloadTrainingAttachment,
      handleDeleteTrainingAttachment,
      handlePreviewTrainingAttachment,
      handleUploadTrainingAttachment,
      loadTrainingAttachments,
      projectFormRef,
      workExperienceFormRef,
      handleAddWorkExperience,
      handleDetailsTabClick,
      showTrainingViewDialog,
      currentTrainingView,
      handleViewTraining,
      educations,
      educationPage,
      educationPageSize,
      educationTotal,
      educationLoading,
      loadEducations,
      handleEducationPageChange,
      handleEducationSizeChange,
      handleViewEducation,
      showEducationDialog,
      educationDialogTitle,
      educationForm,
      showEducationViewDialog,
      currentEducationView,
      handleEditEducation,
      handleDeleteEducation,
      handleAddEducation,
      latestContract,
      handleAddResume, // 新增：暴露 handleAddResume
      handleMainDialogClose,
      handleExportExcel,
      Plus,
      Download,
      View,
      Edit,
      Delete,
      degreeOptions,
      academicDegreeOptions,
      languageLevelOptions,
      // 新增：民族选项
      ethnicityOptions
    }
  }
}
</script>

<style scoped>
.employees-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.header-buttons {
  display: flex;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
  width: 100%;
}

/* 表格容器样式 */
.table-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  min-width: 0;
  overflow-x: auto;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 0px;
  display: flex;
  justify-content: flex-end;
  background: none;
  padding: 0;
  border: none;
}

/* 表格自适应 */
:deep(.el-table) {
  width: 100% !important;
  flex: 1;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
}

:deep(.el-table__inner-wrapper) {
  width: 100% !important;
}

/* 表格列宽度设置 */
:deep(.el-table .el-table__cell) {
  padding: 8px;
}

:deep(.el-table .cell) {
  padding: 0 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 响应式布局 */
@media screen and (max-width: 1366px) {
  :deep(.el-table .cell) {
    padding: 0 4px;
  }

  :deep(.el-button--small) {
    padding: 6px 10px;
    font-size: 12px;
  }
}

@media screen and (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-buttons {
    width: 100%;
    justify-content: flex-start;
  }

  :deep(.el-table .el-button--small) {
    padding: 4px 8px;
    margin: 2px;
  }
}

/* 弹窗样式 */
:deep(.el-dialog) {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: 90vh;
  max-width: 90vw;
}

:deep(.el-dialog__body) {
  flex: 1;
  padding: 20px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  padding: 20px;
  margin: 0;
  border-bottom: 1px solid #dcdfe6;
}

:deep(.el-dialog__footer) {
  padding: 20px;
  margin: 0;
  border-top: 1px solid #dcdfe6;
}

/* 标签页内容区域样式 */
:deep(.el-tabs__content) {
  height: calc(90vh - 260px);
  overflow-y: auto;
  padding-right: 10px;
  padding-bottom: 20px;
}

/* 表单内容区域样式 */
:deep(.el-form) {
  padding-right: 10px;
}

/* 文本框样式 */
:deep(.el-textarea__inner) {
  height: auto !important;
}

:deep(.el-form-item__content .el-textarea__inner) {
  height: 120px !important;
  min-height: 120px !important;
}

/* 专业技能文本框样式 */
:deep(.el-form-item__content .el-textarea__inner[data-field="skills"]) {
  height: 400px !important;
  min-height: 400px !important;
}

/* 描述列表样式 */
:deep(.el-descriptions) {
  padding-right: 10px;
}

.tab-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 富文本内容样式 */
.rich-text-content {
  white-space: pre-wrap;
  line-height: 1.6;
  height: auto;
}

.rich-text-content :deep(img) {
  max-width: 100%;
  height: auto;
}

.rich-text-content :deep(p) {
  margin: 0;
}

.rich-text-content :deep(ul), 
.rich-text-content :deep(ol) {
  margin: 0;
  padding-left: 20px;
}

.rich-text-content :deep(li) {
  margin: 0.5em 0;
}

.rich-text-content :deep(a) {
  color: #409EFF;
  text-decoration: none;
}

.rich-text-content :deep(a:hover) {
  text-decoration: underline;
}

.rich-text-content :deep(table) {
  border-collapse: collapse;
  margin: 1em 0;
  width: 100%;
}

.rich-text-content :deep(th),
.rich-text-content :deep(td) {
  border: 1px solid #dcdfe6;
  padding: 8px;
}

.rich-text-content :deep(th) {
  background-color: #f5f7fa;
}

.preview-section {
  margin-bottom: 30px;
}

.preview-section h3 {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409EFF;
  color: #303133;
}

.resume-preview {
  max-height: calc(90vh - 200px);
  overflow-y: auto;
  padding-right: 10px;
}

.resume-preview :deep(.el-descriptions) {
  margin-bottom: 20px;
}

.resume-preview :deep(.el-table) {
  margin-bottom: 20px;
}

.section-header {
  font-weight: bold;
  color: #303133;
  padding: 10px;
  background-color: #f5f7fa;
  border-right: 1px solid #dcdfe6;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.resume-preview :deep(.el-table) {
  margin-bottom: 0;
}

.resume-preview :deep(.el-descriptions) {
  margin-bottom: 0;
}

.resume-preview :deep(.el-table__row) {
  vertical-align: top;
}

.resume-preview :deep(.el-table__cell) {
  padding: 0;
}

.resume-preview :deep(.el-descriptions__body) {
  margin: 0;
}

.resume-preview :deep(.el-descriptions__table) {
  margin: 0;
}

.resume-preview :deep(.el-descriptions__cell) {
  padding: 8px;
}

.resume-preview :deep(.el-descriptions__label) {
  width: 120px;
  background-color: #f5f7fa;
}

.resume-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
}

.info-container {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
}

.info-row {
  margin: 0 !important;
  border-bottom: 1px solid #d9d9d9;
  display: flex;
}

.info-row:last-child {
  border-bottom: none;
}

.info-label {
  background-color: #f5f7fa;
  padding: 12px 15px;
  text-align: right;
  color: #606266;
  font-weight: bold;
  border-right: 1px solid #d9d9d9;
  border-top: none;
  border-bottom: none; /* 移除下边框，避免重叠 */
  border-left: none;
  min-width: 110px;
  flex-shrink: 0;
  box-sizing: border-box;
}

.info-value {
  padding: 12px 15px;
  color: #303133;
  border-right: 1px solid #d9d9d9;
  border-top: none;
  border-bottom: none; /* 移除下边框，避免重叠 */
  border-left: none;
  flex: 1;
  box-sizing: border-box;
  text-align: left;
}

.info-row .info-value:last-child {
  border-right: none;
}

/* 让所有 info-label、info-value 的高度和边框对齐 */
.info-row > .info-label,
.info-row > .info-value {
  border-top: none;
  border-bottom: none;
  border-left: none;
  box-sizing: border-box;
}

.rich-text-content {
  white-space: pre-wrap;
  line-height: 1.6;
  height: auto;
}

.rich-text-content :deep(p) {
  margin: 0;
}

.rich-text-content :deep(ul),
.rich-text-content :deep(ol) {
  margin: 0;
  padding-left: 20px;
}

/* 表格样式 */
:deep(.el-table) {
  margin-bottom: 20px;
}

:deep(.el-table__header) {
  background-color: #F5F7FA;
}

:deep(.el-table th) {
  background-color: #F5F7FA !important;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-table .el-table__fixed-right) {
  background-color: #fff;
}

:deep(.el-table .el-table__fixed-right th) {
  background-color: #F5F7FA !important;
}

:deep(.el-table .el-table__fixed-right td) {
  background-color: #fff;
}

/* 预览区域样式 */
.resume-preview {
  max-height: calc(90vh - 200px);
  overflow-y: auto;
  padding-right: 10px;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .info-label {
    min-width: 100px;
    padding: 12px 8px;
  }
  
  .info-value {
    padding: 12px 8px;
  }
}

/* 按钮样式优化 */
:deep(.el-button--small) {
  padding: 6px 12px;
  font-size: 13px;
  border-radius: 4px;
  margin: 0 4px;
}

:deep(.el-button--small.is-plain) {
  background-color: #fff;
  border-color: #409EFF;
  color: #409EFF;
}

:deep(.el-button--small.is-plain:hover) {
  background-color: #ecf5ff;
  border-color: #409EFF;
  color: #409EFF;
}

:deep(.el-button--small.is-plain:active) {
  background-color: #409EFF;
  border-color: #409EFF;
  color: #fff;
}

.project-cards {
  display: flex;
  flex-direction: column;
}

.project-card {
  padding: 8px 0;
  position: relative;
}

.project-card:not(:last-child) {
  border-bottom: 1px dashed #dcdfe6;
  margin-bottom: 8px;
}

.project-header {
  margin-bottom: 6px;
}

.project-main-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.project-name {
  font-weight: bold;
  color: #303133;
}

.project-period {
  color: #606266;
  font-size: 14px;
}

.project-divider {
  color: #909399;
}

.project-client, .project-role {
  color: #606266;
}

.project-content {
  font-size: 14px;
  line-height: 1.5;
  padding-left: 2px;
}

.project-desc, .project-resp {
  display: block;
  margin-bottom: 4px;
}

.project-desc {
  margin-bottom: 6px;
}

.project-content .label {
  color: #303133;
  margin-right: 4px;
  display: inline-block;
  min-width: 70px;
  font-weight: bold;
}

.project-content .value {
  color: #303133;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .project-main-info {
    gap: 6px;
  }
}

.work-cards {
  display: flex;
  flex-direction: column;
}

.work-card {
  padding: 8px 0;
  position: relative;
}

.work-card:not(:last-child) {
  border-bottom: 1px dashed #dcdfe6;
  margin-bottom: 8px;
}

.work-header {
  margin-bottom: 6px;
}

.work-main-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.work-company {
  font-weight: bold;
  color: #303133;
}

.work-period {
  color: #606266;
  font-size: 14px;
}

.work-divider {
  color: #909399;
}

.work-position {
  color: #606266;
}

.work-content {
  font-size: 14px;
  line-height: 1.5;
  padding-left: 2px;
}

.work-desc, .work-reason {
  display: block;
  margin-bottom: 4px;
}

.work-desc {
  margin-bottom: 6px;
}

.work-content .label {
  color: #303133;
  margin-right: 4px;
  display: inline-block;
  min-width: 70px;
  font-weight: bold;
}

.work-content .value {
  color: #303133;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .work-main-info {
    gap: 6px;
  }
}

/* 移除固定高度设置 */
.resume-preview .rich-text-content {
  min-height: auto;
  padding: 12px 15px;
}

/* 确保内容区域可以自适应高度 */
.info-value .rich-text-content {
  min-height: auto !important;
  height: auto !important;
}

/* 附件相关样式 */
.attachment-actions {
  display: none;
}

.attachment-filename {
  color: #409EFF;
  cursor: pointer;
}

.attachment-filename:hover {
  text-decoration: underline;
}

.attachment-actions {
  margin-bottom: 16px;
}

.certificate-dialog {
  max-width: 1200px;
}

.dialog-content {
  padding: 20px;
}

.pagination {
  margin-top: 0px;
  display: flex;
  justify-content: flex-end;
}

.contract-attachment-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background: #fafbfc;
  padding: 18px 18px 10px 18px;
  margin-bottom: 16px;
  margin-top: 20px;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.03);
}

.attachment-card-label {
  position: absolute;
  top: -12px;
  left: 16px;
  background: #fff;
  color: #409EFF;
  font-size: 15px;
  font-weight: 500;
  padding: 0 10px;
  z-index: 2;
  border-radius: 8px 8px 8px 0;
  box-shadow: 0 2px 8px 0 rgba(64,158,255,0.04);
  letter-spacing: 2px;
}
.attachment-card-with-label {
  position: relative;
  margin-top: 16px;
}

.attachment-section {
  margin-top: 24px;
  background: #fafbfc;
  border-radius: 8px;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.03);
}

.attachment-card-content {
  padding: 18px 18px 10px 18px;
}

/* 附件卡片样式增强 */
.attachment-card {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  background: #fafbfc;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.03);
  padding: 18px 18px 10px 18px;
}

.detail-label {
  font-weight: bold;
  margin-bottom: 4px;
}
.detail-value {
  margin-bottom: 12px;
}

.info-label, .info-value {
  text-align: center;
}
/* 只让内容部分左对齐，不影响标题 */
.not-center .info-value,
.not-center .project-cards,
.not-center .work-cards,
.not-center .rich-text-content {
  text-align: left !important;
}

.header-buttons .el-button span {
    margin-left: 4px;
}
.table-container .el-button span {
    margin-left: 4px;
}
</style> 